Created
April 2, 2020 07:50
-
-
Save nhudinhtuan/59006787bf5199e08e354f627229a4ee to your computer and use it in GitHub Desktop.
Tree traversal - level order
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
from collections import deque | |
def levelorder_traversal_iterating(root): | |
if not root: | |
return [] | |
result = [] | |
# using queue | |
queue = deque([root]) | |
while queue: | |
# start a new level array | |
result.append([]) | |
current_level_size = len(queue) | |
# visit all items in the current level | |
for i in range(current_level_size): | |
current = queue.popleft() | |
result[-1].append(current.val) | |
if current.left: | |
queue.append(current.left) | |
if current.right: | |
queue.append(current.right) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment