This repository was archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 501
Expand file tree
/
Copy pathTreeLevelOrderPrint.java
More file actions
82 lines (68 loc) · 1.51 KB
/
Copy pathTreeLevelOrderPrint.java
File metadata and controls
82 lines (68 loc) · 1.51 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Program to create a Binary Search Tree and implement level order traversal.
// Author: Viveka Aggarwal
import java.util.LinkedList;
import java.util.Queue;
public class TreeLevelOrderPrint {
node root;
class node {
Integer value;
node left;
node right;
node() {
}
node (Integer value) {
this.value = value;
}
}
public TreeLevelOrderPrint() {
root = new node();
}
public treelevelorderprint(Integer value) {
root = new node(value);
}
public void addToTree(Integer value) {
if (root.value == null) {
root = new node(value);
} else {
addToTree(value, root);
}
}
public void addToTree(Integer value, node curr) {
if (value <= curr.value) {
if (curr.left == null)
curr.left = new node(value);
else
addToTree(value, curr.left);
} else {
if (curr.right == null)
curr.right = new node(value);
else
addToTree(value, curr.right);
}
}
public void levelOrder() {
if (root == null || root.value == null) {
System.out.println();
System.out.println("Empty tree!!!");
return;
}
Queue<node> q = new LinkedList<node>();
q.add(root);
while(!q.isEmpty()) {
node curr = q.poll();
System.out.print(curr.value + " ");
if(curr.left != null)
q.add(curr.left);
if(curr.right != null)
q.add(curr.right);
}
}
public static void main(String[] args) {
TreeLevelOrderPrint tree = new TreeLevelOrderPrint();
for (int i = 0; i <= 10; i++) {
tree.addToTree(i);
}
tree.addToTree(5);
tree.levelOrder();
}
}