mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-23 08:51:31 -04:00
Rename tree_level_traversal.py to tree_bfs.py
This commit is contained in:
parent
00d8c462bf
commit
4530fcce5c
1 changed files with 0 additions and 0 deletions
34
trees/tree_bfs.py
Normal file
34
trees/tree_bfs.py
Normal file
|
@ -0,0 +1,34 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
# 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 level_order(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