I'm somewhat confused between the logic of calculating the height of binary tree.
public static int findHeight(Tree node) {
if(node == null)
return 0;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}
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 ?
If there are n nodes in binary tree, maximum height of the binary tree is n-1 and minimum height is floor(log2n). For example, left skewed binary tree shown in Figure 1(a) with 5 nodes has height 5-1 = 4 and binary tree shown in Figure 1(b) with 5 nodes has height floor(log25) = 2.
The height of an empty tree is 0, and the height of a tree with one node is 1.
The definition is the same for any tree. The height of a tree is the height of any of its children (plus one). So if you have three children you check all three of them and take the greatest + 1 as your height, recursively.
Yes, depending on the order you insert nodes the height of a B-tree may change. However, the tree will always be bushy. A B-tree has the following helpful invariants: All leaves must be the same distance from the source.
The difference all lies in if an empty tree has height -1 or 0.
According to Wikipedia:
The height of a node is the length of the longest downward path to a leaf from that node. The height of the root is the height of the tree. The depth of a node is the length of the path to its root (i.e., its root path).
and
The root node has depth zero, leaf nodes have height zero, and a tree with only a single node (hence both a root and leaf) has depth and height zero. Conventionally, an empty tree (tree with no nodes, if such are allowed) has depth and height −1.
So you might be right - the second one agrees about this.
Of course, these are all definitions - I would not be too amazed to see a definition that agrees with the first version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With