Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
这道题和preorder一样,也是采用分割的方法
postorder: [pL, pL+index-iL+1][pL+index-iL, pR-1][pR]
inorder: [iL, index-1][index][index+1, iR]
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0 || postorder == null
|| postorder.length == 0)
return null;
HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
for (int i = 0; i < inorder.length; i++) {
hashmap.put(inorder[i], i);
}
return helper(hashmap, inorder, 0, inorder.length - 1, postorder, 0,
postorder.length - 1);
}
private TreeNode helper(HashMap<Integer, Integer> hashmap, int[] inorder,
int iL, int iR, int[] postorder, int pL, int pR) {
if (iL > iR || pL > pR)
return null;
TreeNode root = new TreeNode(postorder[pR]);
int index = hashmap.get(root.val);
root.left = helper(hashmap, inorder, iL, index - 1, postorder, pL, pL
+ index - iL - 1);
root.right = helper(hashmap, inorder, index + 1, iR, postorder, pL
+ index - iL, pR - 1);
return root;
}