Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 20, 2021 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/8b06bc607da04bce997be9bb80e83323 to your computer and use it in GitHub Desktop.
Save vrat28/8b06bc607da04bce997be9bb80e83323 to your computer and use it in GitHub Desktop.
Binary tree level order (Python)
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