Connect nodes at same level
Last Updated :
23 Jul, 2025
Given a binary tree, the task is to connect the nodes that are at the same level. Given an addition nextRight pointer for the same.Initially, all the next right pointers point to garbage values, set these pointers to the point next right for each node.
Examples:
Input:

Output:

Explanation: The above tree represents the nextRight pointer connected the nodes that are at the same level.
[Expected Approach - 1] Using Level Order Traversal - O(n) Time and O(n) Space
This idea is to use level order traversal to connect nodes at the same level. A NULL is pushed after each level to track the end of the level. As nodes are processed, each node's nextRight pointer is set to the next node in the queue. If a NULL is encountered and the queue isn't empty, another NULL is added to mark the end of the next level. This ensures that all nodes at the same level are linked. Please refre to Connect Nodes at same Level (Level Order Traversal) for implementation.
[Expected Approach - 2] Using Pre-Order Traversal - O(n) Time and O(n) Space
This approach works only for Complete Binary Trees. In this method we set nextRight in Pre Order manner to make sure that the nextRight of parent is set before its children. When we are at node p, we set the nextRight of its left and right children. Since the tree is complete tree, nextRight of p's left child (p->left->nextRight) will always be p's right child, and nextRight of p's right child (p->right->nextRight) will always be left child of p's nextRight (if p is not the rightmost node at its level). If p is the rightmost node, then nextRight of p's right child will be NULL.
Follow the below steps to Implement the idea:
- Set root ->nextRight to NULL.
- Call for a recursive function of root.
- If root -> left is not NULL then set root -> left -> nextRight = root -> right
- If root -> right is not NULL then
- If root -> nextRight is not NULL set root -> right -> nextRight = root -> nextRight -> left.
- Else set root -> right -> nextRight to NULL.
- recursively call for left of root
- recursively call for right of root
Below is the Implementation of the above approach:
C++
// C++ Program to Connect nodes at same level
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node *nextRight;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
nextRight = nullptr;
}
};
// Set next right of all descendants of root.
// Assumption: root is a complete binary tree
void connectRecur(Node *root) {
if (!root)
return;
// Set the nextRight pointer for root's left child
if (root->left)
root->left->nextRight = root->right;
// Set the nextRight pointer for root's right child
// root->nextRight will be nullptr if root is the
// rightmost child at its level
if (root->right)
root->right->nextRight =
(root->nextRight) ? root->nextRight->left : nullptr;
// Set nextRight for other nodes
// in pre-order fashion
connectRecur(root->left);
connectRecur(root->right);
}
// Sets the nextRight of root and calls connectRecur()
// for other nodes
void connect(Node *root) {
// Set the nextRight for root
root->nextRight = nullptr;
// Set the next right for rest of the
// nodes (other than root)
connectRecur(root);
}
// Function to store the nextRight pointers in
// level-order format and return as a vector of strings
vector<string> getNextRightArray(Node *root) {
vector<string> result;
if (!root)
return result;
queue<Node *> q;
q.push(root);
q.push(nullptr);
while (!q.empty()) {
Node *node = q.front();
q.pop();
if (node != nullptr) {
// Add the current node's data
result.push_back(to_string(node->data));
// If nextRight is nullptr, add '#'
if (node->nextRight == nullptr) {
result.push_back("#");
}
// Push the left and right children to
// the queue (next level nodes)
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
else if (!q.empty()) {
// Add level delimiter for the next level
q.push(nullptr);
}
}
return result;
}
int main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// /
// 3
Node *root = new Node(10);
root->left = new Node(8);
root->right = new Node(2);
root->left->left = new Node(3);
connect(root);
vector<string> output = getNextRightArray(root);
for (const string &s : output) {
cout << s << ' ';
}
cout << endl;
return 0;
}
Java
// Java Program to Connect Nodes
// at same Level
class Node {
int data;
Node left;
Node right;
Node nextRight;
Node(int val) {
data = val;
left = null;
right = null;
nextRight = null;
}
}
class GfG {
// Sets the nextRight of root and calls
// connectRecur() for other nodes
static void connect(Node root) {
// Set the nextRight for root
root.nextRight = null;
// Set the next right for rest of the
// nodes (other than root)
connectRecur(root);
}
// Set next right of all descendants of root.
// Assumption: root is a complete binary tree
static void connectRecur(Node root) {
if (root == null) return;
// Set the nextRight pointer for root's left child
if (root.left != null)
root.left.nextRight = root.right;
// Set the nextRight pointer for root's right child
// root.nextRight will be null if root is the
// rightmost child at its level
if (root.right != null)
root.right.nextRight =
(root.nextRight != null) ? root.nextRight.left : null;
// Set nextRight for other nodes in pre-order fashion
connectRecur(root.left);
connectRecur(root.right);
}
// Function to store the nextRight pointers in level-order format
// and return as a list of strings
static java.util.List<String> getNextRightArray(Node root) {
java.util.List<String> result = new java.util.ArrayList<>();
if (root == null) return result;
java.util.Queue<Node> queue = new java.util.LinkedList<>();
queue.offer(root);
queue.offer(null);
while (!queue.isEmpty()) {
Node node = queue.poll();
if (node != null) {
// Add the current node's data
result.add(Integer.toString(node.data));
// If nextRight is null, add '#'
if (node.nextRight == null) {
result.add("#");
}
// Push the left and right children to the
// queue (next level nodes)
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
} else if (!queue.isEmpty()) {
// Add level delimiter for the next level
queue.offer(null);
}
}
return result;
}
public static void main(String[] args) {
// Constructed binary tree is
// 10
// / \
// 8 2
// /
// 3
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
connect(root);
java.util.List<String> output = getNextRightArray(root);
for (String s : output) {
System.out.print(s + " ");
}
System.out.println();
}
}
Python
# Python Program to Connect Nodes at same Level
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
self.nextRight = None
# Forward declaration of connectRecur
def connectRecur(root):
if not root:
return
# Set the nextRight pointer for root's left child
if root.left:
root.left.nextRight = root.right
# Set the nextRight pointer for root's right child
# root.nextRight will be None if root is the
# rightmost child at its level
if root.right:
root.right.nextRight = root.nextRight.left \
if root.nextRight else None
# Set nextRight for other nodes in pre-order fashion
connectRecur(root.left)
connectRecur(root.right)
# Sets the nextRight of root and calls
# connectRecur() for other nodes
def connect(root):
# Set the nextRight for root
root.nextRight = None
# Set the next right for rest of the
# nodes (other than root)
connectRecur(root)
# Function to store the nextRight pointers
# in level-order format and return as a list
# of strings
def getNextRightArray(root):
result = []
if not root:
return result
queue = [root, None]
while queue:
node = queue.pop(0)
if node is not None:
# Add the current node's data
result.append(str(node.data))
# If nextRight is None, add '#'
if node.nextRight is None:
result.append("#")
# Push the left and right children to the
# queue (next level nodes)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
elif queue:
# Add level delimiter for the next level
queue.append(None)
return result
if __name__ == "__main__":
# Constructed binary tree is
# 10
# / \
# 8 2
# /
# 3
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
connect(root)
output = getNextRightArray(root)
for s in output:
print(s, end=' ')
print()
C#
// C# Program to Connect Nodes at same Level
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left;
public Node right;
public Node nextRight;
public Node(int val) {
data = val;
left = null;
right = null;
nextRight = null;
}
}
class GfG {
// Sets the nextRight of root and calls
// connectRecur() for other nodes
static void connect(Node root) {
// Set the nextRight for root
root.nextRight = null;
// Set the next right for rest of the nodes
// (other than root)
connectRecur(root);
}
// Set next right of all descendants of root.
// Assumption: root is a complete binary tree
static void connectRecur(Node root) {
if (root == null)
return;
// Set the nextRight pointer for root's left child
if (root.left != null)
root.left.nextRight = root.right;
// Set the nextRight pointer for root's right child
// root.nextRight will be null if root is the
// rightmost child at its level
if (root.right != null)
root.right.nextRight = (root.nextRight != null)
? root.nextRight.left
: null;
// Set nextRight for other nodes in
// pre-order fashion
connectRecur(root.left);
connectRecur(root.right);
}
// Function to store the nextRight pointers in
// level-order format and return as a list of strings
static List<string> getNextRightArray(Node root) {
List<string> result = new List<string>();
if (root == null)
return result;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
queue.Enqueue(null);
while (queue.Count > 0) {
Node node = queue.Dequeue();
if (node != null) {
// Add the current node's data
result.Add(node.data.ToString());
// If nextRight is null, add '#'
if (node.nextRight == null) {
result.Add("#");
}
// Push the left and right children to the
// queue (next level nodes)
if (node.left != null)
queue.Enqueue(node.left);
if (node.right != null)
queue.Enqueue(node.right);
}
else if (queue.Count > 0) {
// Add level delimiter for the next level
queue.Enqueue(null);
}
}
return result;
}
static void Main(string[] args) {
// Constructed binary tree is
// 10
// / \
// 8 2
// /
// 3
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
connect(root);
List<string> output = getNextRightArray(root);
foreach(string s in output) {
Console.Write(s + " ");
}
Console.WriteLine();
}
}
JavaScript
// JavaScript Program to Connect
// Nodes at same Level
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
this.nextRight = null;
}
}
// Forward declaration of connectRecur
function connectRecur(root) {
if (!root) return;
// Set the nextRight pointer for root's left child
if (root.left)
root.left.nextRight = root.right;
// Set the nextRight pointer for root's right child
// root.nextRight will be null if root is the
// rightmost child at its level
if (root.right)
root.right.nextRight =
root.nextRight ? root.nextRight.left : null;
// Set nextRight for other nodes in pre-order fashion
connectRecur(root.left);
connectRecur(root.right);
}
// Sets the nextRight of root and calls
// connectRecur() for other nodes
function connect(root) {
// Set the nextRight for root
root.nextRight = null;
// Set the next right for rest of the
// nodes (other than root)
connectRecur(root);
}
// Function to store the nextRight pointers
// in level-order format and return as an array
// of strings
function getNextRightArray(root) {
const result = [];
if (!root) return result;
const queue = [root, null];
while (queue.length > 0) {
const node = queue.shift();
if (node !== null) {
// Add the current node's data
result.push(node.data.toString());
// If nextRight is null, add '#'
if (node.nextRight === null) {
result.push("#");
}
// Push the left and right children to the
// queue (next level nodes)
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
} else if (queue.length > 0) {
// Add level delimiter for the next level
queue.push(null);
}
}
return result;
}
// Constructed binary tree is
// 10
// / \
// 8 2
// /
// 3
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
connect(root);
const output = getNextRightArray(root);
console.log(output.join(' '));
Time Complexity: O(n) where n is the number of Node in Binary Tree.
Auxiliary Space: O(n)
Why this method doesn't work which are not Complete Binary Trees?
Let us consider following tree as an example:
In Method 2, we set the nextRight pointer in pre order fashion. When we are at node 4, we set the nextRight of its children which are 8 and 9 (the nextRight of 4 is already set as node 5). nextRight of 8 will simply be set as 9, but nextRight of 9 will be set as NULL which is incorrect. We can't set the correct nextRight, because when we set nextRight of 9, we only have nextRight of node 4 and ancestors of node 4, we don't have nextRight of nodes in right subtree of root.
Related article:
Connect Nodes at Same Level
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