Algo-Sim › Binary Trees & BST

Maximum Depth of Binary Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

A node's depth is 1 plus the deeper of its two subtrees; an empty tree has depth 0.

Problem

Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.

Constraints

Edge cases to test

Follow-up questions

What is the minimum depth?
The nearest leaf: BFS stops at the first leaf. A node with one child is not a leaf, which trips up min(left, right) + 1 (LC 111).
How do you avoid recursion?
Level-order BFS counting levels: O(n) time and O(width) space.

Solution

Java

public int maxDepth(TreeNode root) {
    if (root == null) return 0;
    int left = maxDepth(root.left);
    int right = maxDepth(root.right);
    return 1 + Math.max(left, right);
}

Python

def max_depth(root):
    if not root:
        return 0
    left = max_depth(root.left)
    right = max_depth(root.right)
    return 1 + max(left, right)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxDepth(TreeNode *root) {
        if (root == nullptr)
            return 0;
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return 1 + std::max(left, right);
    }
};

More Binary Trees & BST problems