您的位置:首页 > 编程语言 > Java开发

Construct Binary Tree from Inorder and Postorder Traversal Java

2014-08-19 17:01 417 查看
Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

 Key to Solve: Recursion + HashMap(Key:inorder's num, Value:position )

    Similar idea as
Construct Binary Tree from Preorder and Inorder Traversal

    beside the top root start from back.

public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length==0 || postorder.length==0) return null;
HashMap<Integer, Integer> map=new HashMap<Integer,Integer>();
//construct map by value and position of inoder
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}

return helperRecur(postorder,inorder,0,postorder.length-1,
0,inorder.length-1,map);
}
private TreeNode helperRecur(int[] postorder,int[] inorder, int postL,
int postR,int inL,int inR,HashMap<Integer,Integer> map){
if(postL>postR || inL>inR){
return null;
}
TreeNode root=new TreeNode(postorder[postR]);
int rootIndex=map.get(root.val);
int distance=rootIndex-inL;

root.left=helperRecur(postorder,inorder,postL,postL+distance-1,
inL,rootIndex-1,map);
root.right=helperRecur(postorder,inorder,postL+distance,postR-1,
rootIndex+1,inR,map);
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode recursion tree
相关文章推荐