-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeWithQueue.java
More file actions
68 lines (62 loc) · 1.55 KB
/
TreeWithQueue.java
File metadata and controls
68 lines (62 loc) · 1.55 KB
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
import java.util.*;
class Node {
int val ;
Node right;
Node left ;
public Node(int val){
this.val = val;
this.right = null;
this.left = null;
}
}
public class TreeWithQueue {
Node root;
public TreeWithQueue(){
this.root = null;
}
void insert(int data){
Node newNode = new Node(data);
if(root==null){
root=newNode;
return;
}
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while (!q.isEmpty()) {
Node current = q.poll();
if (current.left == null) {
current.left = newNode;
return;
} else if (current.right == null) {
current.right = newNode;
return;
}
q.add(current.left);
q.add(current.right);
}
}
public void displayTree() {
display(root, 0);
}
private void display(Node root, int level) {
if (root != null) {
display(root.right, level + 1);
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.val);
display(root.left, level + 1);
}
}
public static void main(String[] args) {
TreeWithQueue tree = new TreeWithQueue();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(2);
tree.insert(4);
tree.insert(6);
tree.insert(8);
tree.displayTree();
}
}