-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculateLevelOfBinaryTree.java
More file actions
101 lines (75 loc) · 2.39 KB
/
Copy pathCalculateLevelOfBinaryTree.java
File metadata and controls
101 lines (75 loc) · 2.39 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Author : Hasnain Memon
* Date : 14/12/2024
*/
import java.util.Scanner;
public class CalculateLevelOfBinaryTree {
private Node root;
static class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
left = right = null;
}
}
public void printPreOrder(Node node) {
if (node == null) {
return;
}
// first print data of node
System.out.print(node.data + " ");
// then recur on left subtree
printPreOrder(node.left);
// then recur on right subtree
printPreOrder(node.right);
}
public void printInOrder(Node node) {
if (node == null) {
return;
}
// first recur on left subtree
printInOrder(node.left);
// then print data of node
System.out.print(node.data + " ");
// then recur on right subtree
printInOrder(node.right);
}
public void printPostOrder(Node node) {
if (node == null) {
return;
}
// first recur on left subtree
printPostOrder(node.left);
// then recur on right subtree
printPostOrder(node.right);
// then print data of node
System.out.print(node.data + " ");
}
// Task 1: Calculate level of the binary tree.
public int calculateLevel(Node root) {
if (root == null) {
return 0;
}
return Math.max(calculateLevel(root.left), calculateLevel(root.right)) + 1;
}
public static void main(String[] args) {
CalculateLevelOfBinaryTree bt = new CalculateLevelOfBinaryTree();
bt.root = new Node(5);
bt.root.left = new Node(4);
bt.root.right = new Node(11);
bt.root.left.left = new Node(2);
bt.root.left.right = new Node(9);
System.out.print("Pre-Order Traversal: ");
bt.printPreOrder(bt.root);
System.out.println();
System.out.print("In-Order Traversal: ");
bt.printInOrder(bt.root);
System.out.println();
System.out.print("Post-Order Traversal: ");
bt.printPostOrder(bt.root);
System.out.println();
// Task 1
System.out.println("Level: " + bt.calculateLevel(bt.root));
}
}