Maximum Depth of Binary Tree

Maximum Depth of Binary Tree – Medium Level Problem

You are given the root of a binary tree, and your task is to determine its depth.

Depth of a binary tree refers to the number of nodes present along the longest path starting from the root node down to the farthest leaf node. 

In simpler terms, it measures how deep the tree goes from the topmost node (the root) to the bottommost node (a leaf with no children). This depth represents the maximum number of steps needed to traverse the tree vertically.

Buy and Sell Stock at right time

Example 1

Graph of Maximum Depth Array

Constraints:

  • 0 <= The number of nodes in the tree <= 100.
  • -100 <= Node.val <= 100

Maximum Depth of Binary Tree

Recommendation for Time and Space Complexity – You should aim for a solution with O(n) time and O(n) space, where n is the number of nodes in the tree.

Hints for solving problems

Hint 1 :

From the definition of binary tree’s maximum depth, Can you think of a way to achieve this recursively? Maybe you should consider the max depth of the subtrees first before computing the maxdepth at the root.

Hint 2 :

We use the Depth First Search (DFS) algorithm to find the maximum depth of a binary tree, starting from the root. For the subtrees rooted at the left and right children of the root node, we calculate their maximum depths recursively going through left and right subtrees. We return 1 + max(leftDepth, rightDepth). Why?

There are mainly 3 approach to solve this problem-

  1. Recursive DFS Method
  2. Iterative DFS(Stack) Method
  3. Breadth First Search Method

1. Recursive DFS Method

In this approach, you use recursion to traverse the tree. At each node, the function is called recursively for the left and right children to calculate their depths. The maximum of these depths is taken, and 1 is added to account for the current node. This method is simple and intuitive for tree traversal.

  • Time complexity: O(n)
  • Space complexity: O(h)
    • Best Case (balanced tree): O(log(n))
    • Worst Case (degenerate tree): O(n)

Where n is the number of nodes in the tree and h is the height of the tree.

Code

2. Iterative DFS(Stack) Method

This method uses a stack to simulate the depth-first traversal iteratively. Each node is paired with its depth and pushed onto the stack. As you process each node, you update the maximum depth by comparing the current depth of the node with the recorded value.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

3. Breadth First Search Method

The BFS method uses a queue to traverse the tree level by level. Nodes at the same depth are processed together. By counting the levels traversed, you determine the maximum depth of the tree. This approach is efficient for level-order traversal.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles