forked from udit034/LeetCode_Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.Construct Binary Tree from Preorder and Inorder Traversal.java
64 lines (51 loc) · 1.52 KB
/
Solution.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class Index
{
int index;
}
TreeNode buildUtil(int in[], int pre[], int inStrt, int inEnd, Index pIndex)
{
// Base case
if (inStrt > inEnd)
return null;
/* Pick current node from Preorder traversal using
postIndex and decrement postIndex */
TreeNode node = new TreeNode(pre[pIndex.index]);
(pIndex.index)++;
/* If this node has no children then return */
if (inStrt == inEnd)
return node;
/* Else find the index of this node in Inorder
traversal */
int iIndex = search(in, inStrt, inEnd, node.val);
/* Using index in Inorder traversal, construct left and
right subtress */
node.left = buildUtil(in, pre, inStrt, iIndex - 1, pIndex);
node.right = buildUtil(in, pre, iIndex + 1, inEnd, pIndex);
return node;
}
int search(int arr[], int strt, int end, int value)
{
int i;
for (i = strt; i <= end; i++)
{
if (arr[i] == value)
break;
}
return i;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
Index pIndex = new Index();
pIndex.index = 0;
return buildUtil(inorder, preorder, 0, inorder.length - 1, pIndex);
}
}