-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path37. ConstructTreeFromInorder&Preorder.java
49 lines (37 loc) · 1.21 KB
/
37. ConstructTreeFromInorder&Preorder.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
/*
class Node {
int data;
Node left, right;
Node(int key) {
data = key;
left = right = null;
}
}
*/
class Solution {
static int preorderIndex = 0;
static HashMap<Integer, Integer> inorderMap;
public static Node buildTree(int inorder[], int preorder[]) {
inorderMap = new HashMap<>();
preorderIndex = 0;
for (int i = 0; i < inorder.length; i++) {
inorderMap.put(inorder[i], i);
}
return constructTree(preorder, 0, inorder.length - 1);
}
private static Node constructTree(int[] preorder, int inorderStart, int inorderEnd) {
if (inorderStart > inorderEnd) return null;
int rootValue = preorder[preorderIndex++];
Node root = new Node(rootValue);
int inorderIndex = inorderMap.get(rootValue);
root.left = constructTree(preorder, inorderStart, inorderIndex - 1);
root.right = constructTree(preorder, inorderIndex + 1, inorderEnd);
return root;
}
public static void printPostorder(Node root) {
if (root == null) return;
printPostorder(root.left);
printPostorder(root.right);
System.out.print(root.data + " ");
}
}