-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathBinaryTree.java
More file actions
43 lines (36 loc) · 992 Bytes
/
BinaryTree.java
File metadata and controls
43 lines (36 loc) · 992 Bytes
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
class TreeNode {
int data;
TreeNode left, right;
public TreeNode(int data) {
this.data = data;
left = right = null;
}
}
class BinaryTree {
TreeNode root;
BinaryTree() {
root = null;
}
int findHeight(TreeNode node) {
if (node == null)
return 0;
int leftHeight = findHeight(node.left);
int rightHeight = findHeight(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
int getHeight() {
return findHeight(root);
}
}
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);
int height = tree.getHeight();
System.out.println("Height of the binary tree is: " + height);
}
}