Tutorialspoint
Problem
Solution
Submissions

Maximum Depth of a Binary Tree

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 8
p>Write a C# function to find the maximum depth of a binary tree. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1
  • Input: root = [3, 9, 20, null, null, 15, 7]
  • Output: 3
  • Explanation:
    • The tree has 3 levels:

       Maximum Depth of a Binary Tree with root node 3
Example 2
  • Input: root = [1, null, 2]
  • Output: 2
  • Explanation:
    • The tree has 2 levels:

      Maximum Depth of a Binary Tree with root node 1
Constraints
  • The number of nodes in the tree is in the range [0, 10^4]
  • -100 ≤ Node.val ≤ 100
  • Time Complexity: O(n)
  • Space Complexity: O(h) where h is the height of the tree
Binary TreePwCKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive depth-first search (DFS) approach
  • For each node, calculate the maximum depth of its left and right subtrees
  • The maximum depth at any node is 1 (the node itself) plus the maximum of the depths of its subtrees
  • Handle the base case where a node is null (depth = 0)

Steps to solve by this approach:

 Step 1: Handle the base case - if the root is null, return 0.
 Step 2: Recursively calculate the maximum depth of the left subtree.
 Step 3: Recursively calculate the maximum depth of the right subtree.
 Step 4: Determine the maximum of the left and right subtree depths.
 Step 5: Return 1 (for the current node) plus the maximum depth found.

Submitted Code :