Compute tree depth directly from a level-order array
A tree visualizer receives binary trees from an API in their compact level-order form, and it needs the tree’s depth to size the canvas before it builds any node objects. Implement depthFromLevels(levels), which reads that array and returns the maximum depth of the tree.
depthFromLevels(levels) // => number
levels[0] is the root.null marks a missing child.null, so trailing nulls may be left out.0 is a normal value. Only null means “no node”.null, is an empty tree with depth 0.levels.// 8
// / \
// 4 12
// / \
// 10 14
depthFromLevels([8, 4, 12, null, null, 10, 14]); // => 3
// 1
// \
// 2
// \
// 3
depthFromLevels([1, null, 2, null, 3]); // => 3
// 1's children: null, 2. Nothing is listed for the missing node.
// 2's children: null, 3.
depthFromLevels([5, 6, 7, 8]); // => 3 (trailing nulls left out)
depthFromLevels([42]); // => 1
depthFromLevels([]); // => 0
depthFromLevels([null]); // => 0