#11
Tree BFS
BFSReturn the values of a binary tree grouped level by level, top to bottom.
function levelOrder(root: TreeNode | null): number[][] {
const res: number[][] = [];
if (!root) return res;
let level: TreeNode[] = [root];
while (level.length) {
const vals: number[] = [];
const next: TreeNode[] = [];
for (const node of level) {
vals.push(node.val);
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
res.push(vals);
level = next;
}
return res;
}TreeNode = Struct.new(:val, :left, :right)
def level_order(root)
return [] unless root
res = []
level = [root]
until level.empty?
res << level.map(&:val)
level = level.flat_map { |node| [node.left, node.right].compact }
end
res
end