Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
和pre & in 是一样的。
1 /** 2 * Definition for binary tree 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 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 return inorder_postorder(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); 15 } 16 public TreeNode inorder_postorder(int[] in, int is, int ie, int[] po, int ps, int pe){ 17 if(ps > pe || is > ie) return null; 18 TreeNode root = new TreeNode(po[pe]); 19 int ind = 0; 20 for(int i = is; i <= ie; i++) 21 if(in[i] == root.val){ 22 ind = i; 23 break; 24 } 25 int len = ind - is; 26 root.left = inorder_postorder(in, is, ind - 1,po, ps, ps + len - 1); 27 root.right = inorder_postorder(in, ind + 1, ie, po, ps + len, pe - 1); 28 return root; 29 } 30 }