Group binary tree values into rows by depth with a max depth
A tournament app draws its bracket as a binary tree: the final at the top, the semi-finals below it, and so on. To lay the bracket out, the renderer needs the matches grouped into rows, one row per round, left to right. On small screens it only draws the top few rounds.
Implement levelRows(root, maxDepth). It returns the tree’s values grouped by depth.
levelRows(root, maxDepth = Infinity) // => Array<Array<value>>
{ value, left, right }. left and right are child nodes, or null, or missing (undefined), which all mean “no child”.root is a node, or null for an empty tree.value can be anything, including falsy values such as 0, '', false and null. A node is present whenever it is an object, whatever its value.0 holds the root’s value, row 1 the values of its children, and so on.maxDepth is given, return only the first maxDepth rows. maxDepth is a non-negative integer or Infinity (the default). 0 returns [].[]. Do not modify the tree.// 8
// / \
// 3 10
// / \ \
// 1 6 14
// / \ /
// 4 7 13
const node = (value, left = null, right = null) => ({ value, left, right });
const root = node(8,
node(3, node(1), node(6, node(4), node(7))),
node(10, null, node(14, node(13))),
);
levelRows(root); // => [[8], [3, 10], [1, 6, 14], [4, 7, 13]]
levelRows(root, 2); // => [[8], [3, 10]]
levelRows(root, 0); // => []
levelRows(null); // => []
levelRows({ value: 0, right: { value: '' } }); // => [[0], ['']]