Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
2014-09-16 10:59
471 查看
Given inorder and postorder traversal of a tree, construct the binary tree.
与Construct Binary Tree from Inorder and Preorder Traversal问题非常类似,唯一区别在于这一次确定root的位置由post traversal来确定,为最后一个元素。
/** * Definition for binary tree * 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.length==0 || postorder.length==0 || inorder.length!=postorder.length) { return null; } int len = inorder.length; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i=0; i<inorder.length; i++) { map.put(inorder[i], i); } return helper(postorder, 0, len-1, inorder, 0, len-1, map); } public TreeNode helper(int[] postorder, int posL, int posR, int[] inorder, int inL, int inR, HashMap<Integer, Integer> map) { if (posL>posR || inL>inR) { return null; } TreeNode root = new TreeNode(postorder[posR]); int index = map.get(postorder[posR]); root.left = helper(postorder, posL, posL+index-1-inL, inorder, inL, index-1, map); root.right = helper(postorder, posL+index-inL, posR-1, inorder, index+1, inR, map); return root; } }
相关文章推荐
- LeetCode_Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: 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]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
- 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
- [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
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal