Binary Tree Level Order Traversal

Binary Tree Level Order Traversal (Leet Code-102)

This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code problem number 102. This is a Leet code problem named Binary Tree Level Order Traversal. We will solve it using python and it is the best space and time-optimized solution. 

Question of Binary Tree Level Order Traversal

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).

This type of searching is also Known as Breadth-first search (BFS). BFS is an algorithm for looking for nodes in a tree data structure that satisfy a specified property. Before moving on to the nodes at the next depth level, it begins at the root of the tree and investigates every node there. To keep track of the child nodes that were encountered but not yet visited, additional memory—typically a queue—is required.

Example

Example 1

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Binary Tree Level Order Traversal
Example 2

Input: root = [1]
Output: [[1]]
Example 3

Input: root = []
Output: []
 

Constraints

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Approach to solve Binary Tree Level Order Traversal

To solve this problem we will first create an empty queue. while traversing from top to bottom we store the left and right child of the node and do the same for them also.

Algorithm

This method performs the following steps for a given input array:

  1. Check for the base case.
  2. ret_lst – variable to store elements.
  3. Create a variable queue to store elements while traversing.
  4. level –  to store the current level of the tree.
  5. Repeat steps 6 to 16 for whole binary tree nodes.
  6. qSize – variable to store the length of the queue.
  7. append the return list to store elements of the current level.
  8. Repeat steps 9 to 14 till qSize greater than zero.
  9. pop the first element and store it in the temp variable.
  10. Append ret_lst[level].append(temp.val).
  11. If the left child exists then add it to the queue.
  12. If the right child exists then add it to the queue.
  13. decrease queue size by one.
  14. End while
  15. Increase the level
  16. End While
  17. Return ret_lst

Python Code for Binary Tree Level Order Traversal

# 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]]:

        #base case
        if root is None:
            return
        
        #variable to store elements
        ret_lst = []

        #queue to store elements while traversing
        queue = []
        #variable to track the current level of tree
        level = 0

        queue.append(root)
        
        #run for whole binary tree nodes
        while queue:
            #variable to store length of queue
            qSize = len(queue)
            #append the return list to store elements of current level
            ret_lst.append([])
            
            #run till qSize greater than zero
            while qSize > 0:    
                #pop the first element
                temp = queue.pop(0)
                ret_lst[level].append(temp.val)
                #if left child exists then add it
                if(temp.left):
                    queue.append(temp.left)
                #if right child exists then add it
                if(temp.right):
                    queue.append(temp.right)
                #decrease queue size by 1
                qSize -= 1
                 
            level+=1           
        return ret_lst 

Complexity Analysis

Time Complexity: O(n)

n is the number of nodes in the binary tree. 

Space Complexity: O(n)

 n is the number of nodes in the binary tree.

Click here for GitHub code

So here is the end of the post. If you find any issues or any questions then write a comment. Share with your friends.

Leave A Comment

Your email address will not be published. Required fields are marked *