https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
Given inorder and postorder traversal of a tree, construct the binary tree.
public TreeNode buildTree(int[] preorder, int[] inorder)
这一题和 Preorder Inorder建树的那题没有太多区别,代码相似度基本90%。原理还是那样,通过找根节点的位置在postorder和inorder相对的位置来确定左右子树在数组的范围,然后不停往下递归。唯一的不同点就在于,preorder的根节点永远在数组或者数组子集的第一个位置,而postorder的根节点永远在数组或者其子集的最后一位。其余情况相同,那么算法步骤就不仔细说了,详细请看Construct Binary Tree from Preorder and Inorder Traversal。
public TreeNode buildTree(int[] inorder, int[] postorder) {
return helper(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
}
public TreeNode helper(int[] inorder, int[] postorder, int in_start, int in_end, int post_start, int post_end){
if(post_start > post_end)
return null;
if(post_start == post_end)
return new TreeNode(postorder[post_start]);
int in_pos = 0;
for(int i = in_start; i <= in_end; i++){
if(postorder[post_end] == inorder[i]){//这里是唯一的不同,preorder用pre_start找,而postorder用post_end来找
in_pos = i;
break;
}
}
TreeNode root = new TreeNode(postorder[post_end]);
root.left = helper(inorder, postorder, in_start, in_pos - 1, post_start, post_start + (in_pos - in_start - 1));
root.right = helper(inorder, postorder, in_pos + 1, in_end, post_start + (in_pos - in_start), post_end - 1);
return root;
}