Walk left, node, right and join the values.
Acceptance criteria
- 1.#out should show 1-2-3.
DSA Tutorial · Trees
These 10 tasks go with the Binary Trees Explained chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “A tree is the first structure where recursion stops being a technique and becomes the natural way to think. A tree is a node with two smaller trees hanging off it — that sentence is the whole subject.” .
1.In-order traversalexercise · easy · 10 min
Walk left, node, right and join the values.
Passes when: #out should show 1-2-3.
2.Pre-order traversalexercise · easy · 10 min · practice plan
Walk node, left, right and join the values.
Passes when: #out should show 2-1-3.
3.Measure the heightexercise · easy · 10 min · practice plan
Report the height of a three-node balanced tree.
Passes when: #out should show height 2.
4.Count the nodesexercise · easy · 10 min · practice plan
Count every node in the tree.
Passes when: #out should show three nodes.
5.Level orderexercise · medium · 10 min · practice plan
Walk breadth first with a queue and join the values.
Passes when: #out should show 2-1-3.
6.Fix the in-order visiting too earlybug fix · easy · 8 min
Pushing before recursing left produces pre-order instead.
Passes when: #out should show 1-2-3.
7.Fix the height counting edgesbug fix · easy · 8 min · practice plan
Returning minus one for an empty tree measures edges, not nodes.
Passes when: #out should show height 2.
8.Fix the count missing a subtreebug fix · easy · 8 min · practice plan
Only recursing left ignores everything on the right.
Passes when: #out should show three nodes.
9.Fix the level order using a stackbug fix · medium · 8 min · practice plan
Popping from the back turns breadth first into depth first.
Passes when: #out should show 2-1-3-4.
10.Fix the missing null guardbug fix · easy · 8 min · practice plan
Without a base case the walk reads properties of null, so a depth cap hides it.
Passes when: #out should show 1-2-3.
Between them these tasks cover Traversal order, Height and Level order.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.