题目:
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
解答:
首先要知道一个结论,前序/后序+中序序列可以唯一确定一棵二叉树,所以自然而然可以用来建树。
看一下中序和后序有什么特点,中序[9,3,15,20,7]
,后序[9,15,7,20,3]
;
有如下特征:
- 后序中右起第一位
3
肯定是根结点,我们可以据此找到中序中根结点的位置rootin
; - 中序中根结点左边就是左子树结点,右边就是右子树结点,即
[左子树结点,根结点,右子树结点]
,我们就可以得出左子树结点个数为int left = rootin - leftin;
; - 后序中结点分布应该是:
[左子树结点,右子树结点,根结点]
; - 根据前一步确定的左子树个数,可以确定后序中左子树结点和右子树结点的范围;
- 如果我们要前序遍历生成二叉树的话,下一层递归应该是:
- 左子树:
root->left = pre_order(中序左子树范围,后序左子树范围,中序序列,后序序列);
; - 右子树:
root->right = pre_order(中序右子树范围,后序右子树范围,中序序列,后序序列);
。
- 左子树:
- 每一层递归都要返回当前根结点
root
;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) return null;
return helper(inorder, postorder, postorder.length - 1, 0, postorder.length - 1);
}
public TreeNode helper(int[] inorder, int[] postorder, int post_last, int in_str, int in_end){
if(in_str > in_end) return null;
int index = 0;
for(int i = in_str; i <= in_end; i++){
if(inorder[i] == postorder[post_last]){
index = i;
}
}
TreeNode root = new TreeNode(postorder[post_last]);
//本题的难点就在于确定后序遍历根节点的位置:post_last - (in_end - index) - 1
//需要好好理解
root.left = helper(inorder, postorder, post_last - (in_end - index) - 1, in_str, index - 1);
root.right = helper(inorder, postorder, post_last - 1, index + 1, in_end);
return root;
}
}