I'm somewhat confused between the logic of calculating the height of binary tree.
Code 1
public static int findHeight(Tree node) {
if(node == null)
return 0;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}
Code 2
public static int findHeight(Tree node) {
if(node == null)
return -1;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}
I think, the second one is correct, since it gives the correct answer for below code :-
Tree t4 = new Tree(4);
Tree t2 = new Tree(2);
Tree t1 = new Tree(1);
Tree t3 = new Tree(3);
Tree t5 = new Tree(5);
t4.left = t2;
t4.right = t5;
t2.left = t1;
t2.right = t3;
// Prints "Height : 2" for Code 2
// Prints "Height : 3" for Code 1
System.out.println("Height : " + findHeight(t4));
I'm confused because many of other SO answers shows the logic for calculating height as per Code 1
Contradictory logics
UPDATE:
All, I've a basic doubt as to what is exactly the height of tree ?
1. Is it the no of nodes between the root and deepest node of tree ( including both - the root & deepest node ) ?
2. Is it the no of edges between the root and deepest node of tree ?
OR
3. Is it just the matter of implementation of every individual - Both approaches are correct ?