102. Binary Tree Level Order Traversal
Apr 2, 2022
Check out the problem description here.
Solution
We can use a queue to store the nodes that are visited level by level.
dequeing is done till current length of the queue, which is the number of nodes in the current level.
whenever a node is dequed from the front , the node which is the child of the dequed node if present is enqued in to the queue.
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
res=[]
q=[]
if root : q.append(root)
while(q):
size=len(q)
inter=[]
for i in range(size):
r=q.pop(0)
inter.append(r.val)
if(r.left):
q.append(r.left)
if(r.right):
q.append(r.right)
res.append(inter)
return res
Time: O(n)
Space : O(n)