←
Atlas · Trees · Topic 7 of 18

Trees

Solve a tree by trusting recursion: answer for the left and right subtrees, then combine at the node.

Spot it

Signals in the question

The input is a TreeNode (binary tree or BST).

The answer for a node depends on the answers for its children (depth, balance, paths).

"Level by level" means BFS with a queue; everything else is usually DFS.

The idea

O(n) time · O(h) for the recursion (h = height) space

Ask each subtree for its answer, then combine. The depth of a tree is 1 plus the deeper of its two subtrees; an empty tree has depth 0. Write the base case first and trust the recursive calls.

Template · DFS, combine children

1def max_depth(root):2    if not root:3        return 04    return 1 + max(max_depth(root.left), max_depth(root.right))

The template, filled in for Maximum Depth of Binary Tree. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
WatchTrees, explainedNeetCode · YouTube · freeReadIntroduction to treesGeeksforGeeks · free

Practice set

Loading your mission…

Common mistakes

1Forgetting the base case (null node), so the recursion crashes.

2Mixing up depth (from the root) and height (from the leaves).

3In a BST, checking only the parent: a node must fit the bounds of all its ancestors.

Check yourself

Question 1 of 2

"Print the tree level by level." Which traversal?