Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
1 class Solution { 2 public TreeNode buildTree(int[] preorder, int[] inorder) { 3 return help(preorder,0,preorder.length-1,inorder,0,inorder.length-1); 4 } 5 private TreeNode help(int[] preorder,int pre_start,int pre_end,int[] inorder,int in_start,int in_end){ 6 if(in_start>in_end || pre_start>pre_end) return null; 7 8 9 TreeNode root = new TreeNode(preorder[pre_start]); 10 int j = in_start; 11 while(preorder[pre_start]!=inorder[j]&& j <=pre_end) 12 j++; 13 //注意下标!!!!!!!! 14 root.left = help(preorder,pre_start+1,pre_start+(j-in_start),inorder,in_start,j-1); 15 root.right = help(preorder,pre_start+(j-in_start)+1,pre_end,inorder,j+1,in_end); 16 return root; 17 } 18 }