So far, I saw 2 different implementations for a max depth of a tree here,
1st one,
max depth === level - 1
: https://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/- Which means, for the base case,
if !node: return -1
- So a three level tree has a max depth of 2
- Which means, for the base case,
2nd one,
max depth === level
: https://leetcode.com/problems/maximum-depth-of-binary-tree/- Which means, for the base case,
if !node: return 0
- So a three level tree has a max depth of 3
- Which means, for the base case,
The implementation in javascript is just as simple as this:
function maxDepth(node){
if (!node) return -1;
return Math.max(maxDepth(node.left),maxDepth(node.right))+1;
}
Which one is correct? What am I missing here?
Also, max depth of a tree is equal to the height of a tree, right? Although it calculates in a different way, depth is from node to root, height is from node to leaf node.