Report the depth of a three-level tree.
Acceptance criteria
- 1.#out should show depth 3.
DSA Tutorial · Trees
These 10 tasks go with the Common Tree Problems 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: “Nearly every tree question is post-order: solve both subtrees, then combine. Once you see that, the code stops being something you memorise.” .
1.Maximum depthexercise · easy · 10 min
Report the depth of a three-level tree.
Passes when: #out should show depth 3.
2.Sum every valueexercise · easy · 10 min · practice plan
Add up all node values.
Passes when: #out should show sum 6.
3.Check balanceexercise · easy · 10 min · practice plan
Report whether the tree is height balanced.
Passes when: #out should show balanced.
4.Count the leavesexercise · easy · 10 min · practice plan
Count nodes with no children.
Passes when: #out should show two leaves.
5.Diameterexercise · medium · 10 min · practice plan
Report the longest path in edges between any two nodes.
Passes when: #out should show diameter 2.
6.Fix the depth using additionbug fix · easy · 8 min
Adding both sides counts nodes rather than measuring the longer path.
Passes when: #out should show depth 3.
7.Fix the sum ignoring the nodebug fix · easy · 8 min · practice plan
Adding only the children leaves the node's own value out.
Passes when: #out should show sum 6.
8.Fix the balance check on a chainbug fix · medium · 8 min · practice plan
A three-node chain is not balanced, so the check must compare heights.
Passes when: #out should show lopsided.
9.Fix the leaf testbug fix · easy · 8 min · practice plan
Counting every node instead of only childless ones overcounts.
Passes when: #out should show two leaves.
10.Fix the diameter measured at the root onlybug fix · easy · 8 min · practice plan
The longest path may sit entirely inside a subtree and never touch the root.
Passes when: #out should show diameter 4.
Between them these tasks cover Post-order, Diameter and Balance.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.