Created
May 20, 2021 08:09
-
-
Save vrat28/8b06bc607da04bce997be9bb80e83323 to your computer and use it in GitHub Desktop.
Binary tree level order (Python)
This file contains 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 | |
class Solution: | |
def levelOrder(self, root): | |
""" | |
:type root: TreeNode | |
:rtype: List[List[int]] | |
""" | |
levels = [] | |
if not root: | |
return levels | |
level = 0 | |
queue = deque([root,]) | |
while queue: | |
# start the current level | |
levels.append([]) | |
# number of elements in the current level | |
level_length = len(queue) | |
for i in range(level_length): | |
node = queue.popleft() | |
# fulfill the current level | |
levels[level].append(node.val) | |
# add child nodes of the current level | |
# in the queue for the next level | |
if node.left: | |
queue.append(node.left) | |
if node.right: | |
queue.append(node.right) | |
# go to next level | |
level += 1 | |
return levels |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment