-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
32 lines (31 loc) · 879 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder, inorder,0,preorder.length-1,0,inorder.length-1);
}
public TreeNode build(int[] preorder, int[] inorder,int ps,int pe,int is,int ie){
if(ps>pe){
return null;
}
int val=preorder[ps];
TreeNode node=new TreeNode(val);
int i = is;
for (; i <=ie; i++) {
if (inorder[i]==val) {
break;
}
}
int rang=i-is;
node.left=build(preorder, inorder,ps+1,ps+rang,is,i-1);
node.right=build(preorder,inorder,ps+rang+1,pe,i+1,ie);
return node;
}
}