Tree Exercises: Practice Problems (with Solutions)
Time to practice. Solve each problem yourself first — sketch a small tree on paper, trace your logic by hand, and reason about time and space complexity before writing code. Only then open the answer sheet. Every View answer link jumps to a full, multi-language solution on the tree solutions page.
How to practice: Almost every tree problem is a short recursion. Decide what each call should return and what the base case is (usually the empty node), and the rest follows. Re-read tree traversals if you get stuck.
All problems use the standard TreeNode from this section.
Warm-ups
Q1. Maximum depth of a binary tree. Return the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0. Target O(n) time.
Q2. Count the leaf nodes. Return how many nodes in a binary tree have no children. State the time and space complexity.
Core problems
Q3. Invert a binary tree. Mirror the tree so every node’s left and right children are swapped, top to bottom. Return the new root. Target O(n).
Q4. Are two trees identical? Given the roots of two binary trees, return true if they have the same structure and the same values at every position.
Q5. Validate a binary search tree. Return true if a binary tree satisfies the BST property at every node — not just locally. Watch out for duplicate-value rules and integer bounds.
Challenge
Q6. Binary tree level-order traversal. Return the node values grouped by level, top to bottom, left to right — a list of lists. Target O(n) time.
Q7. Lowest common ancestor in a BST. Given a BST and two values p and q present in it, return the value of their lowest common ancestor. Aim for O(h) time and O(1) extra space.
Done? Review every solution on the tree answer sheet — even the ones you solved, since there’s often a cleaner recursion. Then continue to heaps.