Created
December 1, 2024 01:19
-
-
Save siavashk/5af80abae2ecc7a6a42de277baa7363a to your computer and use it in GitHub Desktop.
BFS Iterative Binary Tree Traversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# class TreeNode: | |
# def __init__(self, val=0, left=None, right=None): | |
# self.val = val | |
# self.left = left | |
# self.right = right | |
from collections import deque | |
def bfs_iterative_binary_tree_traversal(root: TreeNode): | |
if not root: | |
return | |
queue = deque([root]) | |
while queue: | |
node = queue.popleft() | |
# process the node | |
print(node.val) | |
if node.left: | |
queue.append(node.left) | |
if node.right: | |
queue.append(node.right) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment