LeetCode 102. Binary Tree Level Order Traversal

Description

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

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Explanation

Conduct a breadth-first search for level order traversal. Uses a queue to store the level nodes.

Java Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        
        if (root == null) {
            return result;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            List<Integer> level = new ArrayList<>();
            
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                
                if (node.left != null) {
                    queue.offer(node.left);
                }
                
                if (node.right != null) {
                    queue.offer(node.right);
                }                
            }    
            
            result.add(level);
        }
        
        return result;
    }
}

Python Solution

# 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: TreeNode) -> List[List[int]]:
        results = []
        
        if not root:
            return results
        
        queue = []
        queue.append(root)
        
        while queue:
            level_size = len(queue)
            level = []
            
            for i in range(level_size):
                node = queue.pop(0)
                level.append(node.val)

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

                if node.right:
                    queue.append(node.right)
            results.append(level)
        
        return results
    
  • Time complexity: O(N) since each node is processed exactly once.
  • Space complexity: O(N) to keep the output structure that contains N node values.

2 Thoughts to “LeetCode 102. Binary Tree Level Order Traversal”

  1. Your solution helped me understand Level Order Traversal. Thank you.

    C# Solution :-
    public class Solution {
    public IList<IList> LevelOrder(TreeNode root) {
    List<IList> AllList = new List<IList>();
    var myqueue = new Queue();

    if(root != null)
    myqueue.Enqueue(root);

    while(myqueue.Count>0)
    {
    int len = myqueue.Count;
    var mylist = new List();

    for(int i=0;i<len;i++)
    {
    var node = myqueue.Dequeue();
    mylist.Add(node.val);

    if (node.left != null)
    myqueue.Enqueue(node.left);

    if (node.right != null)
    myqueue.Enqueue(node.right);
    }
    AllList.Add(mylist);
    }
    return AllList;
    }
    }

Leave a Reply

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