102. Binary Tree Level Order Traversal
Leetcode Blind 75
12th Sept 2022 ~ Dion Pinto
Description
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). (Problem)
Code
from collections import deque
# 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]]:
if not root:
return []
q = deque([root])
sol=[[root.val]]
while q:
a=[]
for i in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
a.append(node.left.val)
if node.right:
q.append(node.right)
a.append(node.right.val)
if len(a)!=0:
sol.append(a)
return sol
Time Complexity => o(n)
Space Complexity => o(n) (height of tree)