Binary Tree Max Depth Coding Interview Question | Skilled.dev
Interview Question

Binary Tree Max Depth

Course launching August 2020

Follow me on YouTube for free coding interview videos.

Users who sign up for the email list will receive an exclusive 75% discount at launch.

Your subscription could not be saved. Please try again.
Your subscription was successful! 🤓

Given the root node of a binary tree, write a function findMaxDepth that returns an integer corresponding the maximum depth.

The maximum depth is going to the node with the level furthest from the root. The root node is a 0 depth, and an empty input would be considered -1.

    9      // root = level 0
   / \
  5  22    // level 1
 / \   \
1   7  30  // level 2
      /
     25    // level 3

findMaxDepth(root); // returns 3

The tree nodes will use the following implementation:

class BinaryNode {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

Validate My Answer

  1. This can be solved iteratively or recursively using either DFS or BFS. Follow whichever path you feel most comfortable with, but remember to mention that a recursive solution could have a stack overflow.

    If you do it recursively, you may also need to write it as helper funtion to pass the current depth as a parameter.

  2. All you need to track is the max depth at any point. If the current max you've found is larger than the depth of the current level, then we know to ignore this depth and continue looking.

  3. This can be done in O(n) time and space.