Software interviews
Tree problems for coding interviews: traversals and practice
A tree problem gives you nodes with links to children and asks about its shape: how tall it is, what order its nodes come in, which path is best. Nearly all of them yield to one move, which is to answer for the whole tree by answering for each child subtree and combining the two answers. This page defines the terms from the Open Data Structures text, explains the traversals, gives three patterns with worked examples and four original problems with checked answers.
Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.
Book your first hour ($250)What a tree is, and the words you need
A tree is a set of nodes joined by links with no cycles. A binary tree is one in which each node has at most two children, called left and right. The textbook Open Data Structures defines the words that interview questions lean on. A node’s depth counts the edges on the route from it up to the root. Its height counts the edges on the longest downward route from it to a descendant, and the height of a whole tree is the height of its root. Lengths here are counted in edges, so a tree with a single node has height 0, and it is worth asking an interviewer whether they count edges or nodes.
The same book gives the recursive idea that most tree code is built on. To compute the height of a node, compute the height of its two subtrees, take the maximum and add one. The size of a tree is computed the same way, by adding the sizes of the two subtrees and one. The book also warns about the cost: the maximum depth of the recursion is the maximum depth of a node in the tree, and in a very deep tree the recursive versions can run out of stack space.
MIT OpenCourseWare’s 6.006 Introduction to Algorithms lists binary trees in two lectures, one of which covers AVL trees, and binary heaps, breadth-first search and depth-first search each in their own lecture. The cost figures below are our own reasoning from those definitions, not numbers copied from either source.
| Operation | Cost | Why |
|---|---|---|
| Visit every node, in any traversal order | O(n) | Each node is visited once |
| Height or size by recursion | O(n) | One call per node |
| Extra space for a recursive walk | O(h), the height of the tree | The recursion is as deep as the deepest node |
| Search a binary search tree | O(h) | One comparison per level, going down one path |
| Height of a balanced tree of n nodes | about log n | Each level roughly doubles the node count |
| Height of a tree that is one long chain | n - 1 | Each node has one child |
The last two rows explain why the shape of a tree matters. In a binary search tree, where smaller keys go left and larger keys go right, a search costs about the height. Inserting keys in sorted order builds a chain, and then the search costs O(n). Problem 1 below inserts keys in a deliberately uneven order so that you can see the height grow.
The problem signals that call for each tree technique
Read the statement for the question being asked about the shape.
| Signal in the statement | What it usually means | Technique |
|---|---|---|
| "Height", "depth" or "how many levels" | The answer for a node uses its children | Recursion: 1 plus the larger child answer |
| "Print the nodes in order" or "visit order" | A fixed walk order | Pre-order, in-order or post-order |
| "By level" or "closest to the root first" | Breadth-first | Queue of nodes |
| "Best path from the root" | Choose the better child at each step | Recursion: node value plus the best child path |
| "Longest path between any two nodes" | The path may bend at a node | At each node, join the two tallest child paths |
| "Is this a binary search tree" | Each key must fit between its ancestors | Pass a lower and an upper bound down |
Pattern 1: answer for a node from the answers for its children
The height problem shows the whole pattern. Write what you want for an empty tree, which is -1 edges, and what you want for a node given the answers for its left and right subtrees, which is 1 plus the larger of the two. The code is three lines. Problem 1 builds a binary search tree from a list of keys and asks for its height, and problem 3 changes only the combining step: the best path from the root is the node value plus the larger of the best paths below its children. When the tree is given as a list of parent links instead of node objects, the same idea works by walking up from each leaf, which is a second way to check your answer.
Pattern 2: know the three depth-first orders
A depth-first walk of a binary tree visits a node and its two subtrees in some order. Pre-order visits the node first, in-order visits the left subtree, the node and then the right subtree, and post-order visits both subtrees and then the node. On a binary search tree the in-order walk produces the keys from smallest to largest, which is why it comes up so often. Post-order is the right order when a node needs its children’s results first, as in height or size.
The Open Data Structures text describes the breadth-first alternative: the nodes are visited level by level starting at the root, using a queue that starts with only the root. You take a node from the front, visit it, and add its children at the back. Problem 2 asks which key comes 8th in the post-order of a small search tree, and the way to answer it without error is to write out the order for each subtree before you combine them.
Pattern 3: a path that bends at a node
The diameter of a tree is the number of edges on the longest path between any two nodes, and that path need not pass through the root. Every path has a highest node, where it turns from going up to going down. At each node, the longest path that bends there is the two tallest child paths joined, which in edges is the sum of (child height + 1) for the two taller children. The answer is the best of this over all nodes. You compute heights and the best bend in the same pass, so the cost is O(n). The usual mistake is to return only the height of the root’s children and miss a longer path that lies entirely inside one subtree. Problem 4 is this problem.
Edge cases interviewers probe
- An empty tree. Say what you return: height -1 or 0 depending on the counting you agreed, and 0 for a size.
- A tree with one node, which has height 0 in edges and 1 in nodes.
- A chain, where every node has one child. The recursion is n deep, so mention the stack, and describe the loop version if asked.
- Equal keys in a binary search tree. Ask whether they go left, go right or are rejected, and say what you assume.
- Negative values in a path-sum problem. A path with a negative value can be worse than stopping early, so check whether the path must end at a leaf.
- Counting nodes versus edges. State the unit when you give a height or a diameter.
A good habit is to draw the smallest tree that has the property in the problem, with three or four nodes, and trace your code on it before you call it done.
Four practice problems, in order of difficulty
These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from the height of a search tree to the diameter.
Problem 1. Keys 8, 3, 10, 1, 6, 14, 4, 7, 13, 5, 2 are inserted in that order into an empty binary search tree. Each new key goes left of a node when it is smaller and right when it is larger, starting at the root, and is placed where the search runs out. The tree is not rebalanced. What is its height, counted in edges on the longest path from the root down to a leaf? Give an integer.
Show the answer and the working
Answer: 4
- 8 is the root. 3 and 10 are its children. 1 and 6 go under 3, and 14 goes under 10. 4 goes under 6 on the left, 7 under 6 on the right, and 13 under 14 on the left.
- 5 goes 8, then 3, then 6, then 4, then right of 4. 2 goes 8, 3, 1, then right of 1.
- The path 8, 3, 6, 4, 5 has 4 edges. The next deepest, 8, 3, 1, 2, has 3 edges, and 8, 10, 14, 13 has 3 edges.
- The height is 4. For a tree node, height is 1 plus the larger of its two subtree heights, with an empty tree counted as -1 edges.
Problem 2. The binary search tree built by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13, 5, 2 in that order (smaller keys go left, larger go right) is walked in post-order: left subtree, then right subtree, then the node itself. Which key is visited 8th? Give an integer.
Show the answer and the working
Answer: 13
- The tree: 8 has children 3 and 10. 3 has children 1 and 6. 1 has a right child 2. 6 has children 4 and 7. 4 has a right child 5. 10 has a right child 14, and 14 has a left child 13.
- Post-order of the subtree at 3: first its left subtree, 1 then its right child 2, giving 2, 1. Then the subtree at 6: the subtree at 4 gives 5, 4, then 7 gives 7, then 6 itself. Then 3 itself.
- So far the order is 2, 1, 5, 4, 7, 6, 3, which is seven keys. Then the right subtree of the root: 13, 14, 10. The 8th key is 13.
- The full post-order is 2, 1, 5, 4, 7, 6, 3, 13, 14, 10, 8. A walk visits each node once, so it costs O(n), and the recursion is as deep as the tree is tall.
Problem 3. A tree has 13 nodes numbered 0 to 12, and node 0 is the root. The parent of nodes 1 to 12, in order, is 0, 0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6. The values of nodes 0 to 12, in order, are 5, 3, 8, 2, 9, 4, 7, 6, 1, 10, 2, 12, 3. A path from the root down to a leaf adds up the values of its nodes. What is the largest such sum? Give an integer.
Show the answer and the working
Answer: 29
- Children by parent: node 0 has 1 and 2. Node 1 has 3 and 4. Node 2 has 5 and 6. Node 3 has 7 and 8. Node 4 has 9. Node 5 has 10 and 11. Node 6 has 12. The leaves are 7, 8, 9, 10, 11 and 12.
- Work from the leaves up: the best path from a node is its value plus the larger best path of its children. Node 3 gives 2 + 6 = 8, node 4 gives 9 + 10 = 19, so node 1 gives 3 + 19 = 22. Node 5 gives 4 + 12 = 16, node 6 gives 7 + 3 = 10, so node 2 gives 8 + 16 = 24.
- Node 0 gives 5 + 24 = 29, which is the path 0, 2, 5, 11 with values 5, 8, 4 and 12. The other branch gives 5 + 22 = 27.
- One visit per node makes this O(n). The most common slip is to compare only the two children values instead of the best path under each child.
Problem 4. A tree has 13 nodes numbered 0 to 12, and node 0 is the root. The parent of nodes 1 to 12, in order, is 0, 0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6. The diameter of a tree is the number of edges on the longest path between any two nodes, which need not pass through the root. What is the diameter? Give an integer.
Show the answer and the working
Answer: 6
- For each node, the longest downward path in edges (its height): leaves 7 to 12 have 0, nodes 3, 4, 5 and 6 have 1, nodes 1 and 2 have 2, and node 0 has 3.
- A longest path has a highest node, and through that node it is the two tallest child subtrees joined: the sum of (height of each child + 1). Node 0 has children of height 2 and 2, so a path through it has (2 + 1) + (2 + 1) = 6 edges.
- Node 1 gives (1 + 1) + (1 + 1) = 4 and node 2 gives (1 + 1) + (1 + 1) = 4. Nodes 3 and 5 give (0 + 1) + (0 + 1) = 2, and nodes 4 and 6 give 1, so none of them beats 6.
- The diameter is 6, for example the path 7, 3, 1, 0, 2, 6, 12. One pass computing heights and the best joined pair at each node is O(n).
Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.
These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.
A longer ladder of trees problems
Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 22 problem types that interviewers often use for trees into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.
| Set | Types | Problems to look up | What the set trains |
|---|---|---|---|
| Easy | 9 | walking a tree in pre-order, in-order and post-order; whether a tree is symmetric; the depth of a tree; inverting a tree; the diameter; whether two trees match; whether a tree is balanced; a sum along a path; the average of each level | A recursive walk that returns one value from each subtree |
| Medium | 9 | whether a tree is a valid search tree; level-order and zigzag traversal; building a tree from two traversals; the k-th smallest value in a search tree; the lowest common ancestor; the right side view; a path sum that does not start at the root; flattening a tree to a list; deleting a node from a search tree | A recursive walk that also carries state down, or a level-by-level queue |
| Hard | 4 | the maximum path sum; serializing and deserializing a tree; the fewest cameras that watch every node; the sum of distances from every node | A walk that returns two things at once, or a design with a format of your own |
Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.
Decide early whether the answer for a node depends only on its subtrees, in which case a post-order walk that returns a value suffices, or also on what is above it, in which case you pass state down. Most tree problems reduce to that one choice. Also ask whether the tree is a search tree, since order lets you skip whole branches.
A short routine to practice
- Draw the tree from the statement before you write any code.
- Say what you return for an empty tree, and what you return for a node given its two child answers.
- Pick the traversal order that makes the children available first.
- State the time, O(n), and the stack space, the height of the tree.
- Trace the code on your drawing, node by node.
Questions
What is the difference between depth and height in a tree?
A node’s depth counts the edges on the route from it up to the root. Its height counts the edges on the longest downward route from it to a descendant, and the height of a whole tree is the height of its root.
What are the tree traversal orders?
Pre-order visits a node before its subtrees, in-order visits the left subtree, the node and then the right subtree, and post-order visits both subtrees first. Breadth-first order visits the nodes level by level, using a queue.
How long does a tree traversal take?
A traversal visits each node once, so it takes time proportional to the number of nodes, O(n). A recursive version also uses stack space as deep as the tree is tall.
How a session helps
A session with George is a place to code a problem aloud and have the reasoning questioned: what the answer for an empty tree is, which order you walk in and what the stack looks like on a chain. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.
Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.