Skip to content

Commit 587f192

Browse files
author
Roy
committed
Simplifying height function
1 parent be8b8a1 commit 587f192

1 file changed

Lines changed: 6 additions & 13 deletions

File tree

‎src/com/interview/tree/BinaryTree.java‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -56,21 +56,12 @@ class IntegerRef{
5656
}
5757

5858
public int height(Node root){
59-
IntegerRef ir = new IntegerRef();
60-
heightOfTree(root,ir);
61-
return ir.height;
62-
}
63-
64-
private void heightOfTree(Node root,IntegerRef max){
6559
if(root == null){
66-
max.height = 0;
67-
return;
60+
return 0;
6861
}
69-
IntegerRef irl = new IntegerRef();
70-
IntegerRef irr = new IntegerRef();
71-
heightOfTree(root.left,irl);
72-
heightOfTree(root.right,irr);
73-
max.height = Math.max(irl.height, irr.height) + 1;
62+
int leftHeight = height(root.left);
63+
int rightHeight = height(root.right);
64+
return Math.max(leftHeight, rightHeight) + 1;
7465
}
7566

7667
public static void main(String args[]){
@@ -84,5 +75,7 @@ public static void main(String args[]){
8475
head = bt.addNode(20, head);
8576
head = bt.addNode(-1, head);
8677
head = bt.addNode(21, head);
78+
System.out.println(bt.height(head));
79+
8780
}
8881
}

0 commit comments

Comments
 (0)