Level Order Traversal (Breadth First Search or BFS) of Binary Tree
Last Updated :
31 Jan, 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: [[1], [3, 2], [4], [6, 5]]
How does Level Order Traversal work?
The main idea of level order traversal is to traverse all the nodes of a lower level before moving to any of the nodes of a higher level. This can be done in any of the following ways:
- Using Stack (Recursion)
- Using Queue(Iteration)
[Approach 1] Using Stack (Recursive) – 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++
//Driver Code Starts{
// Recursive C++ program for level order traversal of Binary Tree
#include <iostream>
#include <vector>
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;
}
};
//Driver Code Ends }
// Helper function for recursive level order traversal
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;
}
//Driver Code Starts{
int main() {
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
Node* root = new Node(1);
root->left = new Node(3);
root->right = new Node(2);
root->right->right = new Node(4);
root->right->right->left = new Node(6);
root->right->right->right = new Node(5);
// Perform level order traversal
vector<vector<int>> res = levelOrder(root);
// Print the result
for (vector<int> level : res)
for (int data : level)
cout << data << " ";
}
//Driver Code Ends }
Java
//Driver Code Starts{
// Recursive Java program for level order traversal of Binary Tree
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 = right = null;
}
}
class GfG {
//Driver Code Ends }
// Helper function for recursive level order traversal
static void levelOrderRec(Node root, int level, ArrayList<ArrayList<Integer>> res) {
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
static ArrayList<ArrayList<Integer>> levelOrder(Node root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
levelOrderRec(root, 0, res);
return res;
}
//Driver Code Starts{
public static void main(String[] args) {
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
Node root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(6);
root.right.right.right = new Node(5);
// Perform level order traversal
ArrayList<ArrayList<Integer>> res = levelOrder(root);
// Print the result
for (ArrayList<Integer> level : res) {
for (int data : level) {
System.out.print(data + " ");
}
}
}
}
//Driver Code Ends }
Python
#Driver Code Starts{
# Recursive Python program for level order traversal of Binary Tree
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
#Driver Code Ends }
# Helper function for recursive level order traversal
def levelOrderRec(root, level, res):
if not root:
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
levelOrderRec(root.left, level + 1, res)
levelOrderRec(root.right, level + 1, res)
# Function to perform level order traversal
def levelOrder(root):
res = []
levelOrderRec(root, 0, res)
return res
#Driver Code Starts{
if __name__ == "__main__":
# Create binary tree
# 1
# / \
# 3 2
# \
# 4
# / \
# 6 5
root = Node(1)
root.left = Node(3)
root.right = Node(2)
root.right.right = Node(4)
root.right.right.left = Node(6)
root.right.right.right = Node(5)
# Perform level order traversal
res = levelOrder(root)
# Print the result
for level in res:
for data in level:
print(data, end=" ")
#Driver Code Ends }
C#
//Driver Code Starts{
// Recursive C# program for level order traversal of Binary Tree
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 = right = null;
}
}
class GfG {
//Driver Code Ends }
// Helper function for recursive level order traversal
static void levelOrderRec(Node root, int level, List<List<int>> res) {
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) {
List<List<int>> res = new List<List<int>>();
levelOrderRec(root, 0, res);
return res;
}
//Driver Code Starts{
static void Main(string[] args) {
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
Node root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(6);
root.right.right.right = new Node(5);
// Perform level order traversal
List<List<int>> res = levelOrder(root);
// Print the result
foreach (List<int> level in res) {
foreach (int data in level) {
Console.Write(data + " ");
}
}
}
}
//Driver Code Ends }
JavaScript
//Driver Code Starts{
// Recursive JavaScript program for level order traversal of Binary Tree
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
//Driver Code Ends }
// Helper function for recursive level order traversal
function levelOrderRec(root, level, res) {
if (!root) 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) {
const res = [];
levelOrderRec(root, 0, res);
return res;
}
//Driver Code Starts{
// Driver Code
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
const root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(6);
root.right.right.right = new Node(5);
// Perform level order traversal
let res = levelOrder(root);
// Print the result
res = res.map(level => level.join(" "));
console.log(res.join(" "));
//Driver Code Ends }
[Approach 2] 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++
//Driver Code Starts{
// C++ program for level order traversal of Binary Tree
// Using Queue
#include <iostream>
#include <queue>
#include <vector>
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;
}
};
//Driver Code Ends }
// Iterative method to find height of Binary Tree
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;
}
//Driver Code Starts{
int main() {
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
Node *root = new Node(1);
root->left = new Node(3);
root->right = new Node(2);
root->right->right = new Node(4);
root->right->right->left = new Node(6);
root->right->right->right = new Node(5);
// Perform level order traversal
vector<vector<int>> res = levelOrder(root);
// Print the result
for (vector<int> level : res)
for (int data : level)
cout << data << " ";
}
//Driver Code Ends }
Java
//Driver Code Starts{
// Java program for level order traversal of Binary Tree
// Using Queue
import java.util.*;
class Node {
int data;
Node left, right;
// Constructor to initialize a new node
Node(int value) {
data = value;
left = null;
right = null;
}
}
class GfG {
//Driver Code Ends }
// Iterative method to find height of Binary Tree
static ArrayList<ArrayList<Integer>> levelOrder(Node root) {
if (root == null)
return new ArrayList<>();
// Create an empty queue for level order traversal
Queue<Node> q = new LinkedList<>();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
// Enqueue Root
q.add(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.add(node.left);
// Enqueue right child
if (node.right != null)
q.add(node.right);
}
currLevel++;
}
return res;
}
//Driver Code Starts{
public static void main(String[] args) {
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
Node root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(6);
root.right.right.right = new Node(5);
// Perform level order traversal
ArrayList<ArrayList<Integer>> res = levelOrder(root);
// Print the result
for (ArrayList<Integer> level : res)
for (int data : level)
System.out.print(data + " ");
}
}
//Driver Code Ends }
Python
#Driver Code Starts{
# Python program for level order traversal of Binary Tree
# Using Queue
from collections import deque
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
#Driver Code Ends }
def levelOrder(root):
if root is None:
return []
# Create an empty queue for level order traversal
q = deque()
res = []
# Enqueue Root
q.append(root)
currLevel = 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.popleft()
res[currLevel].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)
currLevel += 1
return res
#Driver Code Starts{
if __name__ == "__main__":
# Create binary tree
# 1
# / \
# 3 2
# \
# 4
# / \
# 6 5
root = Node(1)
root.left = Node(3)
root.right = Node(2)
root.right.right = Node(4)
root.right.right.left = Node(6)
root.right.right.right = Node(5)
# Perform level order traversal
res = levelOrder(root)
# Print the result
for level in res:
for data in level:
print(data, end=" ")
#Driver Code Ends }
C#
//Driver Code Starts{
// C# program for level order traversal of Binary Tree
// Using Queue
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 {
//Driver Code Ends }
// Iterative method to find height of Binary Tree
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;
}
//Driver Code Starts{
static void Main(string[] args) {
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
Node root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(6);
root.right.right.right = new Node(5);
// Perform level order traversal
List<List<int>> res = levelOrder(root);
// Print the result
foreach (List<int> level in res)
foreach (int data in level)
Console.Write(data + " ");
}
}
//Driver Code Ends }
JavaScript
//Driver Code Starts{
// JavaScript program for level order traversal of Binary Tree
// Using Queue
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
//Driver Code Ends }
function levelOrder(root) {
if (root === null)
return [];
// Create an empty queue for level order traversal
const q = [];
const res = [];
// Enqueue Root
q.push(root);
let currLevel = 0;
while (q.length > 0) {
const len = q.length;
res.push([]);
for (let i = 0; i < len; i++) {
// Add front of queue and remove it from queue
const 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;
}
//Driver Code Starts{
// Driver code
// Create binary tree
// 1
// / \
// 3 2
// \
// 4
// / \
// 6 5
const root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(6);
root.right.right.right = new Node(5);
// Perform level order traversal
const res = levelOrder(root);
// Print the result
for (const level of res)
for (const data of level)
console.log(data);
//Driver Code Ends }
Similar Reads
Binary Tree Data Structure
A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree
Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Representation of Binary TreeEach node in a Binar
15+ min read
Properties of Binary Tree
In this post, the properties of a binary tree are discussed: 1. The maximum number of nodes at level 'l' of a binary tree is 2l:Â Note: Here level is the number of nodes on the path from the root to the node (including root and node). The level of the root is 0 This can be proved by induction: For ro
6 min read
Applications, Advantages and Disadvantages of Binary Tree
A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Real-time applications of Binary Trees DOM in HTML.File explorerEvaluate an expressionRouting Algorithms
2 min read
Binary Tree (Array implementation)
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree
Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node. Examples: Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which h
15+ min read
Insertion in a Binary Tree in level order
Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner. Examples: Input: key = 12 Output: Explanation: Node with value 20 is inserted into the binary tree at the first position available in level order manner. Approach:
8 min read
Deletion in a Binary Tree
Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees
A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read