-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105 Construct Binary Tree from Preorder and Inorder Traversal.java
49 lines (45 loc) · 1.44 KB
/
105 Construct Binary Tree from Preorder and Inorder Traversal.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder,int inS,int inE,int preS, int preE) {
if(inS>inE) {
return null;
}
int rootdata=preorder[preS];
TreeNode root=new TreeNode(rootdata);
int rootindex=-1;
for(int i=inS;i<=inE;i++) {
if(inorder[i]==rootdata) {
rootindex=i;
break;
}
}
int leftinS = inS;
int leftinE = rootindex - 1;
int leftpreS = preS + 1;
int leftpreE = leftinE - leftinS + leftpreS;
int rightinS = rootindex + 1;
int rightinE = inE;
int rightpreS = leftpreE + 1;
int rightpreE = preE;
root.left = buildTree(preorder, inorder, leftinS, leftinE, leftpreS, leftpreE);
root.right = buildTree(preorder, inorder, rightinS, rightinE, rightpreS, rightpreE);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree(preorder, inorder, 0, inorder.length-1, 0, preorder.length-1);
}
}