Skip to content

Commit 2f5444e

Browse files
add Height of a Binary Tree - easy
1 parent 97b0fe5 commit 2f5444e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package hackerRank.interviewPreparationKit.trees;
2+
import java.util.*;
3+
4+
class Node {
5+
Node left;
6+
Node right;
7+
int data;
8+
9+
Node(int data) {
10+
this.data = data;
11+
left = null;
12+
right = null;
13+
}
14+
}
15+
16+
class Solution {
17+
public static int height(Node root) {
18+
int leftHeight = 0;
19+
int rightHeight = 0;
20+
21+
if (root.left != null) {
22+
leftHeight = 1 + height(root.left);
23+
}
24+
25+
if (root.right != null) {
26+
rightHeight = 1 + height(root.right);
27+
}
28+
29+
return Math.max(leftHeight, rightHeight);
30+
}
31+
32+
public static Node insert(Node root, int data) {
33+
if(root == null) {
34+
return new Node(data);
35+
} else {
36+
Node cur;
37+
if(data <= root.data) {
38+
cur = insert(root.left, data);
39+
root.left = cur;
40+
} else {
41+
cur = insert(root.right, data);
42+
root.right = cur;
43+
}
44+
return root;
45+
}
46+
}
47+
48+
public static void main(String[] args) {
49+
Scanner scan = new Scanner(System.in);
50+
int t = scan.nextInt();
51+
Node root = null;
52+
while(t-- > 0) {
53+
int data = scan.nextInt();
54+
root = insert(root, data);
55+
}
56+
scan.close();
57+
int height = height(root);
58+
System.out.println(height);
59+
}
60+
}

0 commit comments

Comments
 (0)