Level Order Traversal of a Binary Tree (Leetcode 102)

It makes use of Queue Data Structure. Trick: Pop the node and insert its children in the queue

Problem Link: https://leetcode.com/problems/binary-tree-level-order-traversal/

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        
        if(root is None):
            return []
        
        ans=[]
        q=[root]
        
        while(len(q)>0):
            temp=[]
            
            for i in range(len(q)):
                currnode=q.pop()
                if(currnode.left is not None):
                    q.insert(0,currnode.left)
                if(currnode.right is not None):
                    q.insert(0,currnode.right)
                temp.append(currnode.val)
                
            ans.append(temp)
            
        return ans

Last updated