Level Order Traversal (Breadth First Search or BFS) of Binary Tree
Last Updated :
23 Jul, 2025
Given a Binary Tree, the task is to find its Level Order Traversal. Level Order Traversal technique is a method to traverse a Tree such that all nodes present in the same level are traversed completely before traversing the next level.
Example:
Input:
Output: [[5], [12, 13], [7, 14, 2], [17, 23, 27, 3, 8, 11]]
Explanation: Start with the root → [5]
Level 1: Visit its children → [12, 13]
Level 2: Visit children of 13 and 12 → [7, 14, 2]
Level 3: Visit children of 7,14 and 2→ [17, 23, 27, 3, 8, 11]
How does Level Order Traversal work?
Level Order Traversal visits all nodes at a lower level before moving to a higher level. It can be implemented using:
- Recursion
- Queue (Iterative)
[Naive Approach] Using Recursion - O(n) time and O(n) space
The idea is to traverse the tree recursively, passing the current node and its level, starting with the root at level 0. For each visited node, its value is added to the result array, by considering the value of current level as an index in the result array.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
// Constructor to initialize a new node
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
void levelOrderRec(Node* root, int level, vector<vector<int>>& res) {
// Base case: If node is null, return
if (root == nullptr) return;
// Add a new level to the result if needed
if (res.size() <= level)
res.push_back({});
// Add current node's data to its corresponding level
res[level].push_back(root->data);
// Recur for left and right children
levelOrderRec(root->left, level + 1, res);
levelOrderRec(root->right, level + 1, res);
}
// Function to perform level order traversal
vector<vector<int>> levelOrder(Node* root) {
// Stores the result level by level
vector<vector<int>> res;
levelOrderRec(root, 0, res);
return res;
}
int main() {
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Node* root = new Node(5);
root->left = new Node(12);
root->right = new Node(13);
root->left->left = new Node(7);
root->left->right = new Node(14);
root->right->right = new Node(2);
root->left->left->left = new Node(17);
root->left->left->right = new Node(23);
root->left->right->left = new Node(27);
root->left->right->right = new Node(3);
root->right->right->left = new Node(8);
root->right->right->right = new Node(11);
vector<vector<int>> res = levelOrder(root);
for (vector<int> level : res) {
cout << "[";
for (int i = 0; i < level.size(); i++) {
cout << level[i];
if (i < level.size() - 1) cout << ", ";
}
cout << "] ";
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class Node {
int data;
Node left, right;
// Constructor to initialize a new node
Node(int value) {
data = value;
left = null;
right = null;
}
}
public class GfG {
void levelOrderRec(Node root, int level, List<List<Integer>> res) {
// Base case: If node is null, return
if (root == null) return;
// Add a new level to the result if needed
if (res.size() <= level)
res.add(new ArrayList<>());
// Add current node's data to its corresponding level
res.get(level).add(root.data);
// Recur for left and right children
levelOrderRec(root.left, level + 1, res);
levelOrderRec(root.right, level + 1, res);
}
// Function to perform level order traversal
List<List<Integer>> levelOrder(Node root) {
// Stores the result level by level
List<List<Integer>> res = new ArrayList<>();
levelOrderRec(root, 0, res);
return res;
}
public static void main(String[] args) {
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Node root = new Node(5);
root.left = new Node(12);
root.right = new Node(13);
root.left.left = new Node(7);
root.left.right = new Node(14);
root.right.right = new Node(2);
root.left.left.left = new Node(17);
root.left.left.right = new Node(23);
root.left.right.left = new Node(27);
root.left.right.right = new Node(3);
root.right.right.left = new Node(8);
root.right.right.right = new Node(11);
GfG tree = new GfG();
List<List<Integer>> res = tree.levelOrder(root);
for (List<Integer> level : res) {
System.out.print("[");
for (int i = 0; i < level.size(); i++) {
System.out.print(level.get(i));
if (i < level.size() - 1) System.out.print(", ");
}
System.out.print("] ");
}
}
}
Python
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
def level_order_rec(root, level, res):
# Base case: If node is null, return
if root is None:
return
# Add a new level to the result if needed
if len(res) <= level:
res.append([])
# Add current node's data to its corresponding level
res[level].append(root.data)
# Recur for left and right children
level_order_rec(root.left, level + 1, res)
level_order_rec(root.right, level + 1, res)
# Function to perform level order traversal
def level_order(root):
# Stores the result level by level
res = []
level_order_rec(root, 0, res)
return res
if __name__ == '__main__':
# 5
# / \
# 12 13
# / \ \
# 7 14 2
# / \ / \ / \
#17 23 27 3 8 11
root = Node(5)
root.left = Node(12)
root.right = Node(13)
root.left.left = Node(7)
root.left.right = Node(14)
root.right.right = Node(2)
root.left.left.left = Node(17)
root.left.left.right = Node(23)
root.left.right.left = Node(27)
root.left.right.right = Node(3)
root.right.right.left = Node(8)
root.right.right.right = Node(11)
res = level_order(root)
for level in res:
print(f'[{', '.join(map(str, level))}] ', end='')
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
// Constructor to initialize a new node
public Node(int value) {
data = value;
left = null;
right = null;
}
}
class GfG {
static void LevelOrderRec(Node root, int level, List<List<int>> res) {
// Base case: If node is null, return
if (root == null) return;
// Add a new level to the result if needed
if (res.Count <= level)
res.Add(new List<int>());
// Add current node's data to its corresponding level
res[level].Add(root.data);
// Recur for left and right children
LevelOrderRec(root.left, level + 1, res);
LevelOrderRec(root.right, level + 1, res);
}
// Function to perform level order traversal
static List<List<int>> LevelOrder(Node root) {
// Stores the result level by level
List<List<int>> res = new List<List<int>>();
LevelOrderRec(root, 0, res);
return res;
}
static void Main() {
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Node root = new Node(5);
root.left = new Node(12);
root.right = new Node(13);
root.left.left = new Node(7);
root.left.right = new Node(14);
root.right.right = new Node(2);
root.left.left.left = new Node(17);
root.left.left.right = new Node(23);
root.left.right.left = new Node(27);
root.left.right.right = new Node(3);
root.right.right.left = new Node(8);
root.right.right.right = new Node(11);
List<List<int>> res = LevelOrder(root);
foreach (var level in res) {
Console.Write("[");
for (int i = 0; i < level.Count; i++) {
Console.Write(level[i]);
if (i < level.Count - 1) Console.Write(", ");
}
Console.Write("] ");
}
}
}
JavaScript
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
function levelOrderRec(root, level, res) {
// Base case: If node is null, return
if (root === null) return;
// Add a new level to the result if needed
if (res.length <= level)
res.push([]);
// Add current node's data to its corresponding level
res[level].push(root.data);
// Recur for left and right children
levelOrderRec(root.left, level + 1, res);
levelOrderRec(root.right, level + 1, res);
}
// Function to perform level order traversal
function levelOrder(root) {
// Stores the result level by level
const res = [];
levelOrderRec(root, 0, res);
return res;
}
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
const root = new Node(5);
root.left = new Node(12);
root.right = new Node(13);
root.left.left = new Node(7);
root.left.right = new Node(14);
root.right.right = new Node(2);
root.left.left.left = new Node(17);
root.left.left.right = new Node(23);
root.left.right.left = new Node(27);
root.left.right.right = new Node(3);
root.right.right.left = new Node(8);
root.right.right.right = new Node(11);
const res = levelOrder(root);
for (const level of res) {
process.stdout.write("[");
for (let i = 0; i < level.length; i++) {
process.stdout.write(level[i].toString());
if (i < level.length - 1) process.stdout.write(", ");
}
process.stdout.write("] ");
}
Output[5] [12, 13] [7, 14, 2] [17, 23, 27, 3, 8, 11]
[Expected Approach] Using Queue (Iterative) - O(n) time and O(n) space
Looking at the examples, it's clear that tree nodes need to be traversed level by level from top to bottom. Since the tree structure allows us to access nodes starting from the root and moving downward, this process naturally follows a First-In-First-Out (FIFO) order. So we can use queue data structure to perform level order traversal.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
// Constructor to initialize a new node
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
// Iterative method to perform level order traversal
vector<vector<int>> levelOrder(Node *root) {
if (root == nullptr)
return {};
// Create an empty queue for level order traversal
queue<Node *> q;
vector<vector<int>> res;
// Enqueue Root
q.push(root);
int currLevel = 0;
while (!q.empty()) {
int len = q.size();
res.push_back({});
for (int i = 0; i < len; i++) {
// Add front of queue and remove it from queue
Node *node = q.front();
q.pop();
res[currLevel].push_back(node->data);
// Enqueue left child
if (node->left != nullptr)
q.push(node->left);
// Enqueue right child
if (node->right != nullptr)
q.push(node->right);
}
currLevel++;
}
return res;
}
int main() {
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Node *root = new Node(5);
root->left = new Node(12);
root->right = new Node(13);
root->left->left = new Node(7);
root->left->right = new Node(14);
root->right->right = new Node(2);
root->left->left->left = new Node(17);
root->left->left->right = new Node(23);
root->left->right->left = new Node(27);
root->left->right->right = new Node(3);
root->right->right->left = new Node(8);
root->right->right->right = new Node(11);
vector<vector<int>> res = levelOrder(root);
for (vector<int> level : res) {
cout << "[";
for (int i = 0; i < level.size(); i++) {
cout << level[i];
if (i < level.size() - 1) cout << ", ";
}
cout << "] ";
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Node {
int data;
Node left, right;
// Constructor to initialize a new node
Node(int value) {
data = value;
left = null;
right = null;
}
}
// Iterative method to perform level order traversal
public class GfG{
public static List<List<Integer>> levelOrder(Node root) {
if (root == null)
return new ArrayList<>();
// Create an empty queue for level order traversal
Queue<Node> q = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
// Enqueue Root
q.offer(root);
int currLevel = 0;
while (!q.isEmpty()) {
int len = q.size();
res.add(new ArrayList<>());
for (int i = 0; i < len; i++) {
// Add front of queue and remove it from queue
Node node = q.poll();
res.get(currLevel).add(node.data);
// Enqueue left child
if (node.left != null)
q.offer(node.left);
// Enqueue right child
if (node.right != null)
q.offer(node.right);
}
currLevel++;
}
return res;
}
public static void main(String[] args) {
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Node root = new Node(5);
root.left = new Node(12);
root.right = new Node(13);
root.left.left = new Node(7);
root.left.right = new Node(14);
root.right.right = new Node(2);
root.left.left.left = new Node(17);
root.left.left.right = new Node(23);
root.left.right.left = new Node(27);
root.left.right.right = new Node(3);
root.right.right.left = new Node(8);
root.right.right.right = new Node(11);
// Perform level order traversal and get the result
List<List<Integer>> res = levelOrder(root);
// Print the result in the required format
for (List<Integer> level : res) {
System.out.print("[");
for (int i = 0; i < level.size(); i++) {
System.out.print(level.get(i));
if (i < level.size() - 1) System.out.print(", ");
}
System.out.print("] ");
}
}
}
Python
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
# Iterative method to perform level order traversal
def level_order(root):
if root is None:
return []
# Create an empty queue for level order traversal
q = []
res = []
# Enqueue Root
q.append(root)
curr_level = 0
while q:
len_q = len(q)
res.append([])
for _ in range(len_q):
# Add front of queue and remove it from queue
node = q.pop(0)
res[curr_level].append(node.data)
# Enqueue left child
if node.left is not None:
q.append(node.left)
# Enqueue right child
if node.right is not None:
q.append(node.right)
curr_level += 1
return res
if __name__ == '__main__':
# 5
# / \
# 12 13
# / \ \
# 7 14 2
# / \ / \ / \
#17 23 27 3 8 11
root = Node(5)
root.left = Node(12)
root.right = Node(13)
root.left.left = Node(7)
root.left.right = Node(14)
root.right.right = Node(2)
root.left.left.left = Node(17)
root.left.left.right = Node(23)
root.left.right.left = Node(27)
root.left.right.right = Node(3)
root.right.right.left = Node(8)
root.right.right.right = Node(11)
# Perform level order traversal and get the result
res = level_order(root)
# Print the result in the required format
for level in res:
print('[', end='')
print(', '.join(map(str, level)), end='')
print('] ', end='')
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
// Constructor to initialize a new node
public Node(int value) {
data = value;
left = null;
right = null;
}
}
class GfG {
// Iterative method to perform level order traversal
static List<List<int>> LevelOrder(Node root) {
if (root == null)
return new List<List<int>>();
// Create an empty queue for level order traversal
Queue<Node> q = new Queue<Node>();
List<List<int>> res = new List<List<int>>();
// Enqueue Root
q.Enqueue(root);
int currLevel = 0;
while (q.Count > 0) {
int len = q.Count;
res.Add(new List<int>());
for (int i = 0; i < len; i++) {
// Add front of queue and remove it from queue
Node node = q.Dequeue();
res[currLevel].Add(node.data);
// Enqueue left child
if (node.left != null)
q.Enqueue(node.left);
// Enqueue right child
if (node.right != null)
q.Enqueue(node.right);
}
currLevel++;
}
return res;
}
static void Main() {
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Node root = new Node(5);
root.left = new Node(12);
root.right = new Node(13);
root.left.left = new Node(7);
root.left.right = new Node(14);
root.right.right = new Node(2);
root.left.left.left = new Node(17);
root.left.left.right = new Node(23);
root.left.right.left = new Node(27);
root.left.right.right = new Node(3);
root.right.right.left = new Node(8);
root.right.right.right = new Node(11);
List<List<int>> res = LevelOrder(root);
foreach (List<int> level in res) {
Console.Write("[");
for (int i = 0; i < level.Count; i++) {
Console.Write(level[i]);
if (i < level.Count - 1) Console.Write(", ");
}
Console.Write("] ");
}
}
}
JavaScript
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
// Iterative method to perform level order traversal
function levelOrder(root) {
if (root === null)
return [];
// Create an empty queue for level order traversal
let q = [];
let res = [];
// Enqueue Root
q.push(root);
let currLevel = 0;
while (q.length > 0) {
let len = q.length;
res.push([]);
for (let i = 0; i < len; i++) {
// Add front of queue and remove it from queue
let node = q.shift();
res[currLevel].push(node.data);
// Enqueue left child
if (node.left !== null)
q.push(node.left);
// Enqueue right child
if (node.right !== null)
q.push(node.right);
}
currLevel++;
}
return res;
}
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
const root = new Node(5);
root.left = new Node(12);
root.right = new Node(13);
root.left.left = new Node(7);
root.left.right = new Node(14);
root.right.right = new Node(2);
root.left.left.left = new Node(17);
root.left.left.right = new Node(23);
root.left.right.left = new Node(27);
root.left.right.right = new Node(3);
root.right.right.left = new Node(8);
root.right.right.right = new Node(11);
// Perform level order traversal and get the result
const res = levelOrder(root);
// Print the result in the required format
for (const level of res) {
process.stdout.write('[');
process.stdout.write(level.join(', '));
process.stdout.write('] ');
}
Output[5] [12, 13] [7, 14, 2] [17, 23, 27, 3, 8, 11]
Problems Based on Level Order Traversal
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem