-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFSInBST.java
76 lines (59 loc) · 1.43 KB
/
BFSInBST.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
package conquerred.datastructure;
public class BFSInBST {
private static class Node {
int value;
Node left, right;
public Node(int value) {
this.value = value;
}
}
//insert in the tree
public void insertInTree(Node root, int value) {
if(root.value>value) {
if(root.left!=null) {
insertInTree(root.left, value);
}else {
root.left = new Node(value);
}
}else if(root.value<value) {
if(root.right!=null) {
insertInTree(root.right, value);
}else {
root.right = new Node(value);
}
}
}
//print nodes level wise , it is also called BFS in tree
public int heightoftree(Node root) {
if(root == null)
return 0;
return 1+Math.max(heightoftree(root.left), heightoftree(root.right));
}
public void findLevelNodes(Node root) {
int h = heightoftree(root);
for (int i = 1; i <= h; i++) {
printlevel(root, i);
}
}
public void printlevel(Node root, int h) {
if (root == null)
return;
if(h == 1) {
System.out.println(" the value at each level is : "+root.value);
}else {
printlevel(root.left, h-1);
printlevel(root.right, h-1);
}
}
public static void main(String[] args) {
BFSInBST bst = new BFSInBST();
Node root = new Node(10);
bst.insertInTree(root, 9);
bst.insertInTree(root, 15);
bst.insertInTree(root, 6);
bst.insertInTree(root, 12);
bst.insertInTree(root, 13);
bst.insertInTree(root, 20);
bst.findLevelNodes(root);
}
}