I am currently implementing a Binary Search Tree. My teaching materials state that the depth of a tree is equal to the depth of the deepest leaf. The depth of a node itself is defined as the amount of edges from root to that node. However when I wanted to check if my implementation is correct on the internet, I found that many implementations are like this:
int Tree::Depth()
{
if (!this)
{
return 0;
}
return max(this->left.Depth(), this->right.Depth()) + 1;
}
- http://codercareer.blogspot.be/2013/01/no-35-depth-of-binary-trees.html
- Max depth of Binary search tree
- What's the difference between these two code for find the max depth of a binary tree?
- How to calculate the depth of a binary search tree
But using return 0
gives the amount of nodes instead of the amount of edges (amount of nodes = amount of edges + 1). Shouldn't it be return -1
?
Robert Sedgewick also seems to use -1:
/**
* Returns the height of the BST (for debugging).
*
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
Definition. The size of a tree is its number of nodes. The depth of a node in a tree is the number of links on the path from it to the root. The height of a tree is the maximum depth among its nodes.
~ Algorithms (4th Edition) by Robert Sedgewick and Kevin Wayne
An example of root having depth 0 is visible at page 490 in "Introduction to Algorithms" 3rd. edition by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.
Can someone help me to clear the confusion?