Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Definition for a binary tree node.
- # class TreeNode:
- # def __init__(self, val=0, left=None, right=None):
- # self.val = val
- # self.left = left
- # self.right = right
- class Solution:
- def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
- res = []
- q = collections.deque()
- # add the root to the queue as the base case
- if root: q.append(root)
- # run outer loop till no elements left
- # ensures been through all levels
- while q:
- # num elements at a single level
- qLen = len(q)
- level = []
- # iterate over elements of a single level in one pass
- for i in range(qLen):
- # pop the FIFO element of the queue and append to the result of level
- node = q.popleft()
- level.append(node.val)
- # add to the queue only if there is a child node
- if node.left:
- q.append(node.left)
- # add to the queue only if there is a child node
- if node.right:
- q.append(node.right)
- # append results of the single level
- res.append(level)
- return res
Advertisement
Add Comment
Please, Sign In to add comment