Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
You may assume that duplicates do not exist in the tree.
Solution: recursion
这道题和Construct Binary Tree from Preorder and Inorder Traversal思路完全一样。这里的区别是要从中序遍历和后序遍历中构造出树,算法还是一样,只是现在取根是从后面取(因为后序遍历根是遍历的最后一个元素)。将inorder[]放进hashmap里,然后根据根的值从inorder中取得对应的index。
时间复杂度和空间复杂度也还是O(n)。
( 根据preorder和postorder不能重新构造出树来, 不能唯一确定一棵树)
/** * 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 == null || postorder == null) return null; HashMapmap = new HashMap (); for(int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, map); } public TreeNode helper(int[] inorder, int inL, int inR, int[] postorder, int posL, int posR, HashMap map){ if(inL > inR || posL > posR) return null; TreeNode root = new TreeNode(postorder[posR]); int index = map.get(root.val); root.left = helper(inorder, inL, index-1, postorder, posL, posL+index-inL-1, map); root.right = helper(inorder, index+1, inR, postorder, posR-(inR-index), posR-1, map); return root; } }
No comments:
Post a Comment