Level Order Traversal

In this, the parent is considered after both the left child and right child. Let's say, a tree with node 3 has children node 1 and node 2. Then, in this traversal, we will print node 1 first, then node 3 and node 2 follows.

E.g. [3, 1, 2]

from collections import deque

class Solution:
    def levelOrder(self, root):
        
        if not root:
            return None
        
        result = []
    
        depth = 0
        q = deque()
        q.append(root)
        
        while(q):
            nodes = len(q)
            newList = []
            while nodes:
                node = q.popleft()
                newList.append(node.val)

                if node.left:
                    q.append(node.left)

                if node.right:
                    q.append(node.right)
                
                nodes -= 1
            depth += 1
            result.append(newList)
        
        return result

 

Now, go ahead and solve this problem: https://leetcode.com/problems/binary-tree-level-order-traversal

Discussion

2

0