- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildTree.java
More file actions
Latest commit
40 lines (31 loc) · 865 Bytes
/
Copy pathBuildTree.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
importjava.util.LinkedList;
importjava.util.Queue;
publicclassBuildTree {
publicstaticTreeNodebuildTree(Queue<Integer> queue) {
Queue<TreeNode> node = newLinkedList<>();
TreeNoderoot = newTreeNode(queue.poll());
node.add(root);
while (!node.isEmpty()&&!queue.isEmpty()) {
TreeNodecurr = node.poll();
if(curr.left==null&&!queue.isEmpty()){
intl = queue.poll();
curr.left = newTreeNode(l);
node.add(curr.left);
}
if(curr.right==null&&!queue.isEmpty()){
intr = queue.poll();
curr.right = newTreeNode(r);
node.add(curr.right);
}
}
returnroot;
}
publicstaticvoidmain(String[] args) {
Queue<Integer> queue = newLinkedList<>();
for(inti=1;i<7;i++){
queue.add(i);
}
TreeNoderoot =buildTree(queue);
System.out.println(treeTraversal.inOrderTraversal(root));
}
}