106. Construct Binary Tree from Inorder and Postorder Traversal
- Total Accepted: 74340
- Total Submissions: 239891
- Difficulty: Medium
- Contributors: Admin
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
中序遍历和后序遍历,求原树。 重点在于每次更新index时候,相互之间的数量关系一定搞清楚。最好和 另外一个,根据中序遍历和前序遍历求原树,进行对比。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || postorder == null || inorder.length != postorder.length)
return null;
HashMap<Integer, Integer> hm = new HashMap<Integer,Integer>();
for (int i=0;i<inorder.length;++i)
hm.put(inorder[i], i);
return buildTreePostIn(inorder, 0, inorder.length-1, postorder, 0,
postorder.length-1,hm);
}
private TreeNode buildTreePostIn(int[] inorder, int is, int ie, int[] postorder, int ps, int pe,
HashMap<Integer,Integer> hm){
if (ps>pe || is>ie) return null;
TreeNode root = new TreeNode(postorder[pe]);
int ri = hm.get(postorder[pe]);
root.left = buildTreePostIn(inorder, is, ri-1, postorder, ps, ps+ri-is-1, hm);
root.right = buildTreePostIn(inorder,ri+1, ie, postorder, ps+ri-is, pe-1, hm);
return root;
}
}