106. 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.
本题和之前的105题比较类似,解法可以用相同的想法来解决,代码如下:
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 return helper(postorder.length-1,0,inorder.length-1,inorder,postorder); 13 } 14 public TreeNode helper(int endPost,int startIn,int endIn,int[] inorder,int[] postorder){ 15 if(endPost<0||startIn>endIn) return null; 16 TreeNode root = new TreeNode(postorder[endPost]); 17 int indexIn = 0; 18 for(int i=startIn;i<=endIn;i++){ 19 if(inorder[i]==root.val){ 20 indexIn = i; 21 } 22 } 23 root.left =helper(endPost-1-(endIn-indexIn),startIn,indexIn-1,inorder,postorder); 24 root.right = helper(endPost-1,indexIn+1,endIn,inorder,postorder); 25 return root; 26 } 27 }