Return the level-order traversal of a binary tree's values: left to right, one level at a time.
Pre-order DFS carrying the depth. Append each value to res[depth], creating that level the first time it is reached.
1function levelOrder(root: TreeNode | null): number[][] {2const res: number[][] = [];3function dfs(n: TreeNode | null, d: number) {4if (!n) return;5if (res.length === d) res.push([]);6res[d].push(n.val);7dfs(n.left, d + 1);8dfs(n.right, d + 1);9}10dfs(root, 0);11return res;12}
[]
First node at depth 0: start a new level.
Space: play/pause · ←/→: step