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.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步