How deep does this tree go?
Nested comment threads, category menus and file explorers all arrive as trees, and the first question is usually how deep they go: how far to indent, when to collapse, whether to warn that a reply is nested too far.
Implement maxDepth(node). A node is a plain object shaped { id, children } where children is an array of nodes; the children property may be missing entirely, which means the node has no children. Return the number of levels in the tree: 0 for null, 1 for a node with no children, and one more than the deepest child otherwise.
Arguments
node{ id: unknown; children?: Node[] } | null- The root of the tree, or
nullfor no tree at all.
Returns
number — The number of levels in the tree — 0 for null, 1 for a leaf, one more than the deepest child otherwise.
Examples
maxDepth(null);
// 0maxDepth({ id: "a" });
// 1 — a leaf has depth 1maxDepth({
id: "r",
children: [
{ id: "a" },
{ id: "b", children: [{ id: "c" }] },
],
});
// 3 — the deepest branch winsWhat it has to do
- Return 0 when the node is
null. - Return 1 for a leaf node, whether
childrenis missing or an empty array. - Follow the deepest branch, not the first one.
- Handle trees of any depth.
Notes
- Runs in O(n) time — every node is visited exactly once — and O(h) call-stack space for a tree of height h.
- Deeply nested threads can blow the stack with recursion. If you ever hit that, convert to an iterative traversal with an explicit stack of
{ node, depth }pairs.
Stuck? The javascript course covers everything this challenge needs.
- 1.an absent tree has depth 0
- 2.a leaf has depth 1 with or without a children array
- 3.counts every level of a straight chain
- 4.follows the deepest branch, not the first
- 5.handles a wide but shallow tree
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.