mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-24 09:21:24 -04:00
add some fun tree playing
This commit is contained in:
parent
48720ada4d
commit
bb72bab679
6 changed files with 209 additions and 0 deletions
30
trees_and_graphs/tree_level_traversal.py
Normal file
30
trees_and_graphs/tree_level_traversal.py
Normal 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
|
Loading…
Add table
Add a link
Reference in a new issue