LeetCode 102. Binary Tree Level Order Traversal

Description

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 help 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, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        result = []
        
        if root == None:
            return result
        
        queue = []
        queue.append(root)
        
        while queue:
            level_size = len(queue)
            level = []
            for i in range(0, level_size):
                node = queue.pop(0)
                level.append(node.val)
                
                if node.left != None:
                    queue.append(node.left)
                if node.right != None:
                    queue.append(node.right)
            
            result.append(level)
                                    
        
        return result
  • 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 *