Published 2024-07-07

0104. Maximum Depth of Binary Tree

leetcode

Problem:

Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Solution Description:

To implement the solution for finding the maximum depth of a binary tree, we need to use a depth-first search (DFS) approach. Every time we traverse down a node, we increase our depth count. We need to check both left and right subtrees to find the maximum depth from the current node.

Here's a step-by-step plan:

  1. If the current node is null, that contributes 0 to the depth.
  2. Otherwise, compute the depth of the left and right subtrees.
  3. The depth of the current node is 1 plus the maximum of the depths of the left and right subtrees.
  4. Return this computed depth.

Time Complexity: O(N), where N is the number of nodes in the tree. We have to visit each node once. Space Complexity: O(H), where H is the height of the tree. This is due to the recursion stack.

Example:

Consider the binary tree:

``` 3 / \ 9 20 / \ 15 7 ```

The maximum depth of this tree is 3.

Setup:

Here is a skeleton code for implementing the solution. An additional helper function can also be included for testing purposes using examples.

Test Case 1: Passed (Expected: 3, Got: 3)
Test Case 2: Passed (Expected: 2, Got: 2)
Test Case 3: Passed (Expected: 1, Got: 1)
Test Case 4: Passed (Expected: 0, Got: 0)
Test Case 5: Passed (Expected: 4, Got: 4)
undefined
© d)zharii. sitemap