Skip to main content

One post tagged with "Breadth-First Search"

View All Tags

from functools import reduce

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root) -> list[list[int]]:
result, q = [], [root]
while True:
q = [x for x in q if x]
v = [x.val for x in q]
if not v:
q = reduce(lambda a, b: a + [b.left, b.right], q, [])
return result