0

So far, I saw 2 different implementations for a max depth of a tree here,

  1. 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
  2. 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

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.

Albert Gao
  • 3,653
  • 6
  • 40
  • 69

1 Answers1

0

The terms take different meaning at different places. So, it should be clarified wherever used.


For root, level = 1, depth = 0 and height = 1.

level = depth + 1.

Source: http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/


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). This is commonly needed in the manipulation of the various self-balancing trees, AVL Trees in particular. 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 height −1


Another interesting discussion on What is the difference between tree depth and height?.

Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57