Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
You may assume that duplicates do not exist in the tree.
Hint: this is not necessary a binary-search tree!
01 public TreeNode buildTree(int[] preorder, int[] inorder) {
02 int length=inorder.length;
03 return constructTreeHelper(preorder, inorder, 0, length-1,0,length-1);
04
05 }
06 public TreeNode constructTreeHelper(int[]preorder,int[]inorder, int lo1, int hi1, int lo2, int hi2)
07 {
08 if( lo2>hi2)
09 return null;
10 int root_value=preorder[lo1];
11 TreeNode node=new TreeNode(root_value);
12 int mid=search(inorder, lo2, hi2, root_value);
13 int newhi1=lo1+mid-lo2;
14 node.left=constructTreeHelper(preorder,inorder,lo1+1,lo1+mid-lo2,lo2,mid-1);
15 node.right=constructTreeHelper(preorder,inorder,hi1-hi2+mid+1,hi1,mid+1,hi2);
16 return node;
17
18 }
19 public int search(int []num, int lo, int hi, int target)
20 {
21 for(int i=lo;i<=hi;i++)
22 {
23 if(num[i]==target)
24 return i;
25 }
26 return -1;
27 }
02 int length=inorder.length;
03 return constructTreeHelper(preorder, inorder, 0, length-1,0,length-1);
04
05 }
06 public TreeNode constructTreeHelper(int[]preorder,int[]inorder, int lo1, int hi1, int lo2, int hi2)
07 {
08 if( lo2>hi2)
09 return null;
10 int root_value=preorder[lo1];
11 TreeNode node=new TreeNode(root_value);
12 int mid=search(inorder, lo2, hi2, root_value);
13 int newhi1=lo1+mid-lo2;
14 node.left=constructTreeHelper(preorder,inorder,lo1+1,lo1+mid-lo2,lo2,mid-1);
15 node.right=constructTreeHelper(preorder,inorder,hi1-hi2+mid+1,hi1,mid+1,hi2);
16 return node;
17
18 }
19 public int search(int []num, int lo, int hi, int target)
20 {
21 for(int i=lo;i<=hi;i++)
22 {
23 if(num[i]==target)
24 return i;
25 }
26 return -1;
27 }
没有评论:
发表评论