Maximum Depth of Binary Tree

Pattern: Depth, diameter and balance

easy

The depth of a tree is 1 for its root plus the larger depth of its two subtrees; an empty tree has depth 0.

The problem

Return the number of nodes on the longest path from the root down to a leaf. [3, 9, 20, null, null, 15, 7] gives 3. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What is the depth of an empty tree?
  • If you know both subtrees' depths, what is the tree's?
  • Can level order give it too?

Hints

    Brute force, and why it fails

    Find every root-to-leaf path and take the longest: O(n × h).

    The key insight

    The depth of a node depends only on its children's depths, so one post-order pass gives it.

    Dry run

    depth(9)1

    [3, 9, 20, null, null, 15, 7]. The leaves 9, 15 and 7 have depth 1 from below.

    Step 1 of 3

    The plan

    depth(n) = 0 if n is null else 1 + max(depth(n.left), depth(n.right))
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each node once; the recursion is as deep as the tree.

    Edge cases

    • Empty tree.
    • One node.
    • A long chain, where recursion is n deep.
    I've built my logic, show the code

    Java

    class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null) return 0;
            return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));   // this node plus the deeper side
        }
    }

    C++

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (root == NULL) return 0;
            return 1 + max(maxDepth(root->left), maxDepth(root->right));   // this node plus the deeper side
        }
    };

    Python

    class Solution:
        def maxDepth(self, root) -> int:
            if not root:
                return 0
            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))   # this node plus the deeper side

    Common mistakes

    • Counting edges instead of nodes.
    • Taking the smaller depth.

    Similar problems