您的位置:首页 > 其它

LeetCode Construct Binary Tree from Inorder and Postorder Traversal

2015-08-21 03:03 423 查看
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

这道题与Construct Binary Tree from Preorder and Inorder Traversal 思路相似,不同之处在于这里的root在postorder的最有一位,其他都相同,由inorder找出分切点。

Time O(n), Space O(n).

Note:
在recursion调用时postorder的index更新一定会用到(index-inL). 我刚开始很凑巧的写成了postR = index-1, 第一次循
环恰巧相等,但之后就不对了。

AC Java:

/**
* 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 == 0|| postorder.length == 0 || 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 helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, hm);
}
private TreeNode helper(int[] inorder,int inL,int inR, int[] postorder,int postL,int postR, HashMap<Integer, Integer> hm){
if(inL>inR || postL>postR){
return null;
}
TreeNode root = new TreeNode(postorder[postR]);
int index = hm.get(root.val);
root.left = helper(inorder, inL, index-1, postorder, postL, index-inL+postL-1, hm); //error
root.right = helper(inorder, index+1, inR, postorder, index-inL+postL, postR-1, hm);
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: