forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstructBinaryTreefromPreorderandInorderTraversal.java
49 lines (35 loc) · 1.24 KB
/
ConstructBinaryTreefromPreorderandInorderTraversal.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
class Solution {
private TreeNode root = null;
private int indexInPreorder = 0;
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0|| inorder.length==0){
return null;
}
root = buildTreeHelper(preorder, inorder, 0 ,inorder.length-1);
return root;
}
private TreeNode buildTreeHelper(int[] preorder, int[] inorder, int startInorder, int endInorder){
if(indexInPreorder>=preorder.length){
return null;
}
TreeNode newNode = new TreeNode(preorder[indexInPreorder]);
int indexInOrder = indexInInorder(inorder, startInorder, endInorder, preorder[indexInPreorder]);
if(indexInOrder==-1){
// Null
return null;
}
indexInPreorder++;
newNode.left = buildTreeHelper(preorder, inorder, startInorder, indexInOrder-1);
newNode.right = buildTreeHelper(preorder, inorder, indexInOrder+1, endInorder);
return newNode;
}
private int indexInInorder(int[] inorder, int start, int end, int no){
while(start<=end){
if(no==inorder[start]){
return start;
}
start++;
}
return -1;
}
}