Rename tree_level_traversal.py to tree_bfs.py

This commit is contained in:
marina 2023-08-01 15:21:59 -07:00 committed by GitHub
parent 00d8c462bf
commit 4530fcce5c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

34
trees/tree_bfs.py Normal file
View 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