Skip to main content

Pattern · 21 problems

Binary Tree Interview Problems

Tree problems reward trust. I decide what a call returns for its subtree, then combine at the current node.

Get the link for your laptop

Free: write the code and run it, no sign-up.

When I reach for it

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.
  • A binary search tree hands you an order for free.

Problems, easiest first

7 easy · 11 medium · 3 hard. Open one to read it, then write it in the free editor.

The idea

Trust the recursion. Decide what one call returns for its subtree. Then combine the left answer and the right answer at the current node.

Ask two questions. What does this node need from its children? What does it pass up to its parent? Those two answers can differ.

def depth(node):
    if node is None:
        return 0                   # an empty tree has depth 0
    left = depth(node.left)        # trust the call for each subtree
    right = depth(node.right)
    return 1 + max(left, right)    # combine at this node
Depth of a tree. The base case, two trusted calls, and one combining line. Most tree problems fit this shape. Python shown; the idea carries to every language in the editor.

Where it goes wrong

  • Skipping the base case for an empty node.
  • Mixing up what a call returns with what you track on the side.
  • Walking a whole binary search tree when its order lets you skip half.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

Where Coco comes in

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.

Questions people ask

Should I write trees recursively or iteratively?
Write the recursion first, since it matches the tree. Switch to an explicit stack if the interviewer worries about depth.
Which traversal order should I use?
Pre-order handles a node before its children. In-order gives sorted values from a search tree. Post-order lets children report first.

Meet these next

Fin and Coco are characters, not people. strongyes.io is independent. Leo builds it with AI agents.