File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
src/main/java/HackerRank/interviewPreparationKit/trees Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments