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
相关文章推荐
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- leetcode--Construct Binary Tree from Inorder and Postorder Traversal
- leetcode - Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [面试真题] LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- functionclass[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode::Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode 79] 106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode_Construct Binary Tree from Inorder and Postorder Traversal