</>

104. Maximum Depth of Binary Tree

Easy NeetCode 150
Trees Time O(N) Space O(H)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Trees
Time
O(N)
Space
O(H)

Standard Solution (C++)

SummaryGiven the root of a binary tree, find the maximum depth — the number of nodes along the longest path from the root down to the farthest leaf node.

Approach
  • Use recursive DFS: the depth of any node is 1 plus the maximum depth of its two subtrees.
  • Base case: a null node contributes 0 to the depth.
  • This bottom-up recursion naturally propagates the longest path length back to the root.
  • Alternatively, BFS level-order traversal counts levels explicitly, but recursion is more concise.
#include <algorithm>
using namespace std;

// Definition for a binary tree node (provided by LeetCode).
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    // Recursive DFS: depth = 1 + max(left depth, right depth)
    int maxDepth(TreeNode* root) {
        if (!root) return 0;                          // empty subtree contributes nothing
        int leftDepth  = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
        return 1 + max(leftDepth, rightDepth);        // current node adds one level
    }
};
Time O(n) Space O(h) where h is the tree height; O(log n) for balanced trees, O(n) worst case (skewed tree)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        return max(maxDepth(root->left), maxDepth(root->right))+1;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space). 
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N).
Time O(N) Space O(H)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern