106 construct tree with inorder
2017-10-24 本文已影响0人
Fei_JOB
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null) return null;
if(inorder.length != postorder.length) return null;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < inorder.length; i++){
map.put(inorder[i], i);
}
int len = inorder.length;
return helper(inorder, 0, len-1, postorder, 0, len -1, map);
}
public TreeNode helper(int[] inorder, int s1, int e1, int[] postorder, int s2, int e2, Map<Integer, Integer> map){
if(s2 > e2) return null;
TreeNode node = new TreeNode(postorder[e2]);
if(s2 == e2) return node;
int inPos = map.get(postorder[e2]);
int numLeft = inPos - s1;
node.left = helper(inorder, s1, inPos-1, postorder, s2, s2+ numLeft -1, map);
node.right = helper(inorder, inPos + 1, e1, postorder, s2+numLeft, e2-1, map);
return node;
}
}