您的位置:首页 > 其它

Construct Binary Tree from Inorder and Postorder Traversal

2017-01-07 16:49 197 查看

1.题目

根据中序遍历和后序遍历树构造二叉树

注意事项

你可以假设树中不存在相同数值的节点

给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]

返回如下的树:

  2

 /  \

1    3

2.算法

我们可以从后序遍历中找出根节点,从中序遍历中找出左右子树,并用递归解答题

public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder==null || postorder==null || inorder.length==0 || postorder.length==0)
{
return null;
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<inorder.length;i++)
{
map.put(inorder[i],i);
}
return helper(inorder,postorder,0,inorder.length-1, 0, postorder.length-1,map);
}
private TreeNode helper(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR, HashMap<Integer, Integer> map)
{
if(inL>inR || postL>postR)
return null;
TreeNode root = new TreeNode(postorder[postR]);
int index = map.get(root.val);
root.left = helper(inorder,postorder,inL,index-1,postL,postL+index-inL-1,map);
root.right = helper(inorder,postorder,index+1,inR,postR-(inR-index),postR-1,map);
return root;
}
原帖地址

http://blog.csdn.net/linhuanmars/article/details/24390157
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: