Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
本来想先对inorder array做预处理存上val对应的index,结果发现 val可能有duplicates。
1 /**duplicates 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[] preorder, int[] inorder) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 return preorder_inorder(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); 15 } 16 public TreeNode preorder_inorder(int[] pre, int ps, int pe, int[] in, int is, int ie){ 17 if(ps > pe || is > ie) return null; 18 TreeNode root = new TreeNode(pre[ps]); 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 = preorder_inorder(pre, ps + 1, ps + len, in, is, ind - 1); 27 root.right = preorder_inorder(pre, ps + 1 + len, pe, in, ind + 1, ie); 28 return root; 29 } 30 }