LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题解:
这道题与Construct Binary Tree from Preorder and Inorder Traversal思路相似,不同之处在于这里的root在postorder的最有一位,其他都相同,由inorder找出分切点.
Time Complexity: O(n). Space: O(n).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode buildTree(int[] inorder, int[] postorder) { 12 if(inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0){ 13 return null; 14 } 15 HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); 16 for(int i = 0; i<inorder.length; i++){ 17 hm.put(inorder[i], i); 18 } 19 return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, hm); 20 } 21 22 private TreeNode helper(int [] inorder, int inL, int inR, int [] postorder, int posL, int posR, HashMap<Integer, Integer> hm){ 23 if(inL > inR || posL > posR){ 24 return null; 25 } 26 TreeNode root = new TreeNode(postorder[posR]); 27 int rootIndex = hm.get(postorder[posR]); 28 root.left = helper(inorder, inL, rootIndex-1, postorder, posL, posL+rootIndex-inL-1, hm); 29 root.right = helper(inorder, rootIndex+1, inR, postorder, posL+rootIndex-inL, posR-1, hm); 30 return root; 31 } 32 }
类似Construct Binary Tree from Preorder and Postorder Traversal.