-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildTree.java
More file actions
40 lines (31 loc) · 865 Bytes
/
BuildTree.java
File metadata and controls
40 lines (31 loc) · 865 Bytes
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
import java.util.LinkedList;
import java.util.Queue;
public class BuildTree {
public static TreeNode buildTree(Queue<Integer> queue) {
Queue<TreeNode> node = new LinkedList<>();
TreeNode root = new TreeNode(queue.poll());
node.add(root);
while (!node.isEmpty()&&!queue.isEmpty()) {
TreeNode curr = node.poll();
if(curr.left==null&&!queue.isEmpty()){
int l = queue.poll();
curr.left = new TreeNode(l);
node.add(curr.left);
}
if(curr.right==null&&!queue.isEmpty()){
int r = queue.poll();
curr.right = new TreeNode(r);
node.add(curr.right);
}
}
return root;
}
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
for(int i=1;i<7;i++){
queue.add(i);
}
TreeNode root =buildTree(queue);
System.out.println(treeTraversal.inOrderTraversal(root));
}
}