Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
You may assume that duplicates do not exist in the tree.
Solution:
1. Construct root from the last element in post-order.
2. Find root's index(hash map) in in-order, and then we can decide its left sub-tree and right sub-tree.
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
// inorder value ---> index
HashMap map = new HashMap();
for(int i = 0; i < inorder.length; i++)
map.put(inorder[i], i);
return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, map);
}
// build up the tree recursively
public TreeNode helper(int[] inorder, int i_beg, int i_end, int[] postorder, int p_beg, int p_end, HashMap map){
if(i_beg > i_end || p_beg > p_end)
return null;
int root_val = postorder[p_end];
TreeNode root = new TreeNode(root_val);
int i = map.get(root_val);
root.left = helper(inorder, i_beg, i-1, postorder, p_beg, p_beg + i-1-i_beg, map);
root.right = helper(inorder, i+1, i_end, postorder, p_beg + i-1-i_beg + 1, p_end-1, map);
return root;
}
}

No comments:
Post a Comment