Skip to content

Commit 4e41b2d

Browse files
committed
level order btree recurssion
1 parent 8f013ca commit 4e41b2d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Trees/levelOrderbtree.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
class Node {
3+
int data;
4+
Node left;
5+
Node right;
6+
7+
Node(int data) {
8+
this.data = data;
9+
left = right = null;
10+
}
11+
}
12+
13+
class BinaryTree {
14+
Node root;
15+
16+
BinaryTree() {
17+
root = null;
18+
}
19+
20+
BinaryTree(int data) {
21+
this.root = new Node(data);
22+
}
23+
24+
int height(Node root)
25+
{
26+
if (root == null)
27+
return -1;
28+
return 1 + Math.max(height(root.left), height(root.right));
29+
}
30+
31+
void printAtLevel(Node root, int level)
32+
{
33+
if (root == null)
34+
return;
35+
if (level == 1) {
36+
System.out.print(root.data + " ");
37+
return;
38+
}
39+
printAtLevel(root.left, level - 1);
40+
printAtLevel(root.right, level - 1);
41+
}
42+
43+
void levrec(Node root)
44+
{
45+
if (root == null)
46+
return;
47+
int h = height(root);
48+
for (int i = 1; i <= h + 1; i++) {
49+
printAtLevel(root, i);
50+
System.out.println();
51+
}
52+
}
53+
}
54+
55+
class levelOrderbtree {
56+
public static void main(String[] args) {
57+
58+
BinaryTree bt = new BinaryTree(2);
59+
bt.root.left = new Node(3);
60+
bt.root.right = new Node(5);
61+
bt.root.left.right = new Node(9);
62+
bt.root.right.left = new Node(7);
63+
bt.levrec(bt.root);
64+
}
65+
}

0 commit comments

Comments
 (0)