中序和后序构造二叉树

106.从中序与后序遍历序列构造二叉树

给定两个整数数组 inorderpostorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树

示例 1:

img

1
2
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:

1
2
输入:inorder = [-1], postorder = [-1]
输出:[-1]

提示:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorderpostorder 都由 不同 的值组成
  • postorder 中每一个值都在 inorder
  • inorder 保证是树的中序遍历
  • postorder 保证是树的后序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return traverasl(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
}

public TreeNode traverasl(int[] inorder , int inleft ,int inright ,int[] postorder, int postleft, int postright ){
//没有元素了
if(inright<inleft) return null;

//取后序序列最右元素作为值创建节点
int rootVal = postorder[postright];
TreeNode root = new TreeNode(rootVal);

int index = 0;
for(index = inleft; index<=inright ; index++){
if(inorder[index]==rootVal) break;//找到了分隔点
}
//中序左数组的大小与后续左数组大小相同,index-inleft为中序左数组大小
int left_len = index - inleft;
root.left = traverasl(inorder, inleft, index-1, postorder, postleft, postleft + left_len - 1);
root.right= traverasl(inorder, index+1, inright, postorder, postleft + left_len, postright - 1);

return root;
}
}

中序和后序构造二叉树
http://example.com/2023/04/09/算法/二叉树/16. 中序遍历与后序遍历构造二叉树/
作者
PALE13
发布于
2023年4月9日
许可协议