-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstructBinaryTreeInorderPreorder.java
96 lines (79 loc) · 2.56 KB
/
ConstructBinaryTreeInorderPreorder.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package techQuestions;
/*
Purpose: Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
Author: Erich Meissner
Date: 5/6/20
Time: 2:05 PM
*/
import java.util.HashMap;
import java.util.List;
public class ConstructBinaryTreeInorderPreorder {
int preOrderIndex = 0;
int inorderArr[];
int preorderArr[];
HashMap<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] preorder) {
this.inorderArr = inorder;
this.preorderArr = preorder;
// we know that the first value in the preorder is
// the root of this binary tree
// preOrderIndex = 0;
// System.out.println(preorderArr[preOrderIndex]);
// construct a hash map where key = node.val
// and value = index in inorder array
int i = 0;
for (int num: inorderArr) {
map.put(num, i);
i++;
}
TreeNode root = helper(0, preorderArr.length);
System.out.println(root.val);
return root;
}
public TreeNode helper(int left, int right) {
// recursive base case if to check if left has
// become larger than right
if (left == right) {
return null;
}
// the preorder index is the root of this
// current recursion
TreeNode root = new TreeNode(preorderArr[preOrderIndex]);
// System.out.println(root.val);
// now, find the index of this root value in the inorder array
int in_index = map.get(root.val);
// System.out.println(in_index);
//for the next recursion, the new root will be 1 larger
//than current pre order index
preOrderIndex++;
//build left subtree
root.left = helper(left, in_index);
//build right subtree
root.right = helper(in_index+1, right);
return root;
}
}
class mainConstruct{
public static void main(String[] args) {
int inorder[] = {9,3,15,20,7};
int preorder[] = {3,9,20,15,7};
ConstructBinaryTreeInorderPreorder constructTree
= new ConstructBinaryTreeInorderPreorder();
TreeNode root = constructTree.buildTree(inorder, preorder);
List<List<Integer>> levelorder = root.levelOrder(root);
for (List thisList: levelorder) {
System.out.println(thisList.toString());
}
}
}