add some fun tree playing

This commit is contained in:
bt3gl 2023-07-29 14:28:17 -07:00 committed by GitHub
parent 48720ada4d
commit bb72bab679
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 209 additions and 0 deletions

View file

@ -0,0 +1,30 @@
# Given the root of a binary tree, return the level order traversal of its nodes' values.
# (i.e., from left to right, level by level).
def levelOrder(root: Optional[TreeNode]) -> list[list[int]]:
if root is None:
return []
queue = collections.deque()
queue.append(root)
result = []
while queue:
this_level = []
for _ in range(len(queue)):
current = queue.popleft()
if current:
this_level.append(current.val)
queue.append(current.left)
queue.append(current.right)
if this_level:
result.append(this_level)
return result