Connect nodes at same level using constant extra space
Last Updated :
13 Feb, 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 nextRight 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.
Using Recursion - O(n) Time and O(h) Space
The idea is to traverse the nextRight node before the left and right children to ensure that all nodes at level i have their nextRightset before moving to level i+1. Starting from the root node, for each node, first connect its left child (if it exists) to the next right node. To do this, traverse the nextRight node of the parent until a notNULL child is found, then connect the left child to this first not NULL node. Similarly, connect the right child to the nextright node. Afterward, recursively traverse the right child first to ensure all right nodes are connected, followed by the left child.
Below is the implementation:
C++
// C++ Program to Connect nodes at same level
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right, *nextRight;
Node(int item) {
data = item;
left = right = nextRight = nullptr;
}
};
// Function to find the next right node
Node *getNextRight(Node *p) {
// Start with the nextRight of the current node
Node *temp = p->nextRight;
while (temp != nullptr) {
// If the left child exists, return it
if (temp->left != nullptr)
return temp->left;
// If the right child exists, return it
if (temp->right != nullptr)
return temp->right;
// Move to the next node at the same level
temp = temp->nextRight;
}
// Return nullptr if no next right node exists
return nullptr;
}
void connectRecur(Node *p)
{
// Base case
if (p == nullptr)
return;
// Set nextRight for left child
if (p->left) {
if (p->right) {
p->left->nextRight = p->right;
}
else {
p->left->nextRight = getNextRight(p);
}
}
// Set nextRight for right child
if (p->right) {
p->right->nextRight = getNextRight(p);
}
// Recur for the right child first
// Ensures nextRight pointers are set for
// all nodes at the current level
connectRecur(p->right);
// Recur for the left child
connectRecur(p->left);
}
Node* connect(Node *root)
{
if (!root)
return nullptr;
// Set nextRight of root
root->nextRight = nullptr;
// Call the recursive function
connectRecur(root);
return root;
}
// Function to get the array representation of nextRight links
vector<string> printTree(Node *root) {
vector<string> result;
// If the tree is empty, return an empty vector
if (!root)
return result;
// Use a queue for level-order traversal
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 to the result
result.push_back(to_string(node->data));
// If nextRight is nullptr, add '#' to the result
if (node->nextRight == nullptr) {
result.push_back("#");
}
// Push the left and right children to the queue
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
else if (!q.empty()) {
// Add a level delimiter (nullptr) 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);
// resultant root after modifying the tree
// as given in problem
Node* resRoot=connect(root);
vector<string> output = printTree(resRoot);
for (const string &s : output) {
cout << s << ' ';
}
cout << endl;
return 0;
}
C
// C Program to Connect nodes at same level
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right, *nextRight;
};
// Function to create a new node
struct Node* newNode(int item) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = item;
node->left = node->right = node->nextRight = NULL;
return node;
}
// Function to find the next right node
struct Node *getNextRight(struct Node *p) {
// Start with the nextRight of the current node
struct Node *temp = p->nextRight;
while (temp != NULL) {
// If the left child exists, return it
if (temp->left != NULL)
return temp->left;
// If the right child exists, return it
if (temp->right != NULL)
return temp->right;
// Move to the next node at the same level
temp = temp->nextRight;
}
// Return NULL if no next right node exists
return NULL;
}
void connectRecur(struct Node *p) {
// Base case
if (p == NULL)
return;
// Set nextRight for left child
if (p->left) {
if (p->right) {
p->left->nextRight = p->right;
}
else {
p->left->nextRight = getNextRight(p);
}
}
// Set nextRight for right child
if (p->right) {
p->right->nextRight = getNextRight(p);
}
// Recur for the right child first
// Ensures nextRight pointers are set for
// all nodes at the current level
connectRecur(p->right);
// Recur for the left child
connectRecur(p->left);
}
struct Node* connect(struct Node *root) {
if (!root)
return NULL;
// Set nextRight of root
root->nextRight = NULL;
// Call the recursive function
connectRecur(root);
return root;
}
// Function to get the array representation of nextRight links
void printTree(struct Node *root) {
// If the tree is empty, return
if (!root)
return;
// Use a queue for level-order traversal
struct Node *queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
queue[rear++] = NULL;
while (front < rear) {
struct Node *node = queue[front++];
if (node != NULL) {
// Print the current struct Node's data
printf("%d ", node->data);
// If nextRight is NULL, print '#'
if (node->nextRight == NULL) {
printf("# ");
}
// Push the left and right children to the queue
if (node->left)
queue[rear++] = node->left;
if (node->right)
queue[rear++] = node->right;
} else if (front < rear) {
// Add a level delimiter (NULL) for the next level
queue[rear++] = NULL;
}
}
}
int main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// /
// 3
struct Node *root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
// resultant root after modifying the tree
// as given in problem
struct Node* resRoot=connect(root);
printTree(resRoot);
printf("\n");
return 0;
}
Java
// Java Program to Connect nodes at same level
import java.util.*;
class Node {
int data;
Node left, right, nextRight;
Node(int item) {
data = item;
left = right = nextRight = null;
}
}
// Class containing methods to connect nodes
class GfG {
// Function to find the next right node
static Node getNextRight(Node p) {
// Start with the nextRight of the current node
Node temp = p.nextRight;
while (temp != null) {
// If the left child exists, return it
if (temp.left != null)
return temp.left;
// If the right child exists, return it
if (temp.right != null)
return temp.right;
// Move to the next node at the same level
temp = temp.nextRight;
}
// Return null if no next right node exists
return null;
}
static void connectRecur(Node p) {
// Base case
if (p == null)
return;
// Set nextRight for left child
if (p.left != null) {
if (p.right != null) {
p.left.nextRight = p.right;
} else {
p.left.nextRight = getNextRight(p);
}
}
// Set nextRight for right child
if (p.right != null) {
p.right.nextRight = getNextRight(p);
}
// Recur for the right child first
// Ensures nextRight pointers are set for
// all nodes at the current level
connectRecur(p.right);
// Recur for the left child
connectRecur(p.left);
}
static Node connect(Node root) {
if (root == null)
return null;
// Set nextRight of root
root.nextRight = null;
// Call the recursive function
connectRecur(root);
return root;
}
// Function to get the array representation of nextRight links
List<String> printTree(Node root) {
List<String> result = new ArrayList<>();
// If the tree is empty, return an empty list
if (root == null)
return result;
// Use a queue for level-order traversal
Queue<Node> q = new LinkedList<>();
q.add(root);
q.add(null);
while (!q.isEmpty()) {
Node node = q.poll();
if (node != null) {
// Add the current node's data to the result
result.add(String.valueOf(node.data));
// If nextRight is null, add '#' to the result
if (node.nextRight == null) {
result.add("#");
}
// Push the left and right children to the queue
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
} else if (!q.isEmpty()) {
// Add a level delimiter (null) for the next level
q.add(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);
GfG tree = new GfG();
// resultant root after modifying the tree
// as given in problem
Node resRoot =tree.connect(root);
List<String> output = tree.printTree(resRoot);
for (String s : output) {
System.out.print(s + " ");
}
System.out.println();
}
}
Python
# Python program to connect nodes at the same level
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.nextRight = None
# Function to find the next right node
def getNextRight(p):
# Start with the nextRight of the current node
temp = p.nextRight
while temp is not None:
# If the left child exists, return it
if temp.left is not None:
return temp.left
# If the right child exists, return it
if temp.right is not None:
return temp.right
# Move to the next node at the same level
temp = temp.nextRight
# Return None if no next right node exists
return None
def connectRecur(p):
# Base case
if p is None:
return
# Set nextRight for left child
if p.left:
if p.right:
p.left.nextRight = p.right
else:
p.left.nextRight = getNextRight(p)
# Set nextRight for right child
if p.right:
p.right.nextRight = getNextRight(p)
# Recur for the right child first
# Ensures nextRight pointers are set for
# all nodes at the current level
connectRecur(p.right)
# Recur for the left child
connectRecur(p.left)
def connect(root):
if not root:
return None
# Set nextRight of root
root.nextRight = None
# Call the recursive function
connectRecur(root)
return root
# Function to get the array representation of nextRight links
def printTree(root):
result = []
# If the tree is empty, return an empty list
if not root:
return result
# Use a queue for level-order traversal
q = []
q.append(root)
q.append(None)
while q:
node = q.pop(0)
if node is not None:
# Add the current node's data to the result
result.append(str(node.data))
# If nextRight is None, add '#' to the result
if node.nextRight is None:
result.append("#")
# Push the left and right children to the queue
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
elif q:
# Add a level delimiter (None) for the next level
q.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)
resRoot = connect(root)
output = printTree(resRoot)
print(" ".join(output))
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right, nextRight;
public Node(int val) {
data = val;
left = right = nextRight = null;
}
}
class GfG {
// Function to find the next right node
static Node getNextRight(Node p) {
// Start with the nextRight of the current node
Node temp = p.nextRight;
while (temp != null) {
// If the left child exists, return it
if (temp.left != null)
return temp.left;
// If the right child exists, return it
if (temp.right != null)
return temp.right;
// Move to the next node at the same level
temp = temp.nextRight;
}
// Return null if no next right node exists
return null;
}
static void connectRecur(Node p) {
if (p == null)
return;
// Set the nextRight for left child
if (p.left != null) {
if (p.right != null) {
p.left.nextRight = p.right;
}
else
p.left.nextRight = getNextRight(p);
}
// Set the nextRight for right child
if (p.right != null)
p.right.nextRight = getNextRight(p);
// Recur for the right child first
// Ensures nextRight pointers are set for
// all nodes at the current level
connectRecur(p.right);
// Recur for the left child
connectRecur(p.left);
}
// Function to set nextRight for all nodes
static Node connect(Node root) {
if (root == null)
return null;
// Set nextRight of root
root.nextRight = null;
// Call the recursive function
connectRecur(root);
return root;
}
static List<string> printTree(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);
Node resRoot= connect(root);
List<string> output = printTree(resRoot);
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;
}
}
// Function to find the next right node
function getNextRight(p) {
// Start with the nextRight of the current node
let temp = p.nextRight;
while (temp !== null) {
// If the left child exists, return it
if (temp.left !== null)
return temp.left;
// If the right child exists, return it
if (temp.right !== null)
return temp.right;
// Move to the next node at the same level
temp = temp.nextRight;
}
// Return null if no next right node exists
return null;
}
function connectRecur(p) {
// Base case
if (p == null)
return;
// Set nextRight for left child
if (p.left) {
if (p.right) {
p.left.nextRight = p.right;
}
else {
p.left.nextRight = getNextRight(p);
}
}
// Set nextRight for right child
if (p.right) {
p.right.nextRight = getNextRight(p);
}
// Recur for the right child first
// Ensures nextRight pointers are set for
// all nodes at the current level
connectRecur(p.right);
// Recur for the left child
connectRecur(p.left);
}
/* Sets nextRight of all nodes of a tree with root as p */
function connect(root) {
if(!root)
return null;
//set nextRight of root
root.nextRight = null;
//call the recursive function
connectRecur(root);
return root;
}
// Function to store the nextRight pointers
// in level-order format and return as an array
// of strings
function printTree(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);
const resRoot = connect(root);
const output = printTree(resRoot);
console.log(output.join(' '));
Time Complexity : O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(h), where h accounts to the additional recursive stack
[Expected Approach] Using Iteration - O(n) Time and O(1) Space
The idea is to execute the above approach iteratively minimizing the recursion stack. To do so, we traverse the nextRight node before the left and right children (root, nextRight, left), then we can make sure that all nodes at level i have the nextRight set, before the level i+1 nodes. We use nestedloop where the outer loop, goes through all the levels and the inner loop goes through all the nodes at every level.
C++
// C++ Program to Connect nodes at same level
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right, *nextRight;
Node(int val) {
data = val;
left = right = nextRight = nullptr;
}
};
// Function to find the next right node
Node *getNextRight(Node *p) {
// Start with the nextRight of the current node
Node *temp = p->nextRight;
while (temp != nullptr) {
// If the left child exists, return it
if (temp->left != nullptr)
return temp->left;
// If the right child exists, return it
if (temp->right != nullptr)
return temp->right;
// Move to the next node at the same level
temp = temp->nextRight;
}
// Return nullptr if no next right node exists
return nullptr;
}
// Function to connect nodes at the same level
Node* connect(Node *root) {
Node *temp;
// If the tree is empty, return
if (!root)
return nullptr ;
// Initialize the root's nextRight to nullptr
root->nextRight = nullptr;
// Traverse nodes level by level
while (root != nullptr) {
Node *q = root;
// Traverse all nodes at the current level
while (q != nullptr) {
// If the left child exists
if (q->left) {
// If the right child also exists, connect it
if (q->right)
q->left->nextRight = q->right;
// Otherwise, connect to the next right node
else
q->left->nextRight = getNextRight(q);
}
// If the right child exists, connect it to the next right node
if (q->right)
q->right->nextRight = getNextRight(q);
// Move to the next node at the same level
q = q->nextRight;
}
// Move to the next level starting with the leftmost node
if (root->left)
root = root->left;
else if (root->right)
root = root->right;
else
root = getNextRight(root);
}
return root;
}
// Function to get the array representation of nextRight links
vector<string> printTree(Node *root) {
vector<string> result;
// If the tree is empty, return an empty vector
if (!root)
return result;
// Use a queue for level-order traversal
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 to the result
result.push_back(to_string(node->data));
// If nextRight is nullptr, add '#' to the result
if (node->nextRight == nullptr) {
result.push_back("#");
}
// Push the left and right children to the queue
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
else if (!q.empty()) {
// Add a level delimiter (nullptr) 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);
Node* resRoot= connect(root);
vector<string> output = printTree(root);
for (const string &s : output) {
cout << s << ' ';
}
cout << endl;
return 0;
}
C
// C Program to Connect nodes at same level
#include <stdio.h>
#include <stdlib.h>
// Structure for a binary tree node
struct Node {
int data;
struct Node *left, *right, *nextRight;
};
// Helper function to create a new node
struct Node *newNode(int val) {
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->data = val;
node->left = node->right = node->nextRight = NULL;
return node;
}
// Function to find the next right node at the same level
struct Node *getNextRight(struct Node *p) {
struct Node *temp = p->nextRight;
while (temp != NULL) {
if (temp->left)
return temp->left;
if (temp->right)
return temp->right;
temp = temp->nextRight;
}
return NULL;
}
// Function to connect nodes at the same level
struct Node* connect(struct Node *root) {
if (!root)
return NULL;
root->nextRight = NULL;
struct Node *tempRoot = root;
// Traverse nodes level by level
while (root != NULL) {
struct Node *q = root;
// Traverse all nodes at the current level
while (q != NULL) {
// Connect left child
if (q->left) {
if (q->right)
q->left->nextRight = q->right;
else
q->left->nextRight = getNextRight(q);
}
// Connect right child
if (q->right)
q->right->nextRight = getNextRight(q);
// Move to next node in the current level
q = q->nextRight;
}
// Move to the next level (first available child)
if (root->left)
root = root->left;
else if (root->right)
root = root->right;
else
root = getNextRight(root);
}
return tempRoot;
}
// Function to get the array representation of nextRight links
void printTree(struct Node *root) {
if (!root)
return;
struct Node *queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
queue[rear++] = NULL;
while (front < rear) {
struct Node *node = queue[front++];
if (node != NULL) {
printf("%d ", node->data);
if (node->nextRight == NULL) {
printf("# ");
}
if (node->left)
queue[rear++] = node->left;
if (node->right)
queue[rear++] = node->right;
} else if (front < rear) {
queue[rear++] = NULL;
}
}
}
int main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// /
// 3
struct Node *root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
// Connect nodes at the same
// level and get the modified root
root = connect(root);
// Print the tree with nextRight connections
printTree(root);
printf("\n");
return 0;
}
Java
// Java Program to Connect nodes at same level
import java.util.*;
class Node {
int data;
Node left, right, nextRight;
// Constructor to initialize a node with data
Node(int val) {
data = val;
left = right = nextRight = null;
}
}
public class GfG {
// Function to find the next right node
Node getNextRight(Node p) {
Node temp = p.nextRight;
while (temp != null) {
if (temp.left != null)
return temp.left;
if (temp.right != null)
return temp.right;
temp = temp.nextRight;
}
return null;
}
// Function to connect nodes at the same level
Node connect(Node root) {
if (root == null)
return null;
root.nextRight = null;
Node tempRoot = root;
while (root != null) {
Node q = root;
// Traverse all nodes at the current level
while (q != null) {
if (q.left != null) {
if (q.right != null)
q.left.nextRight = q.right;
else
q.left.nextRight = getNextRight(q);
}
if (q.right != null)
q.right.nextRight = getNextRight(q);
q = q.nextRight;
}
// Move to the next level starting
// with the leftmost node
if (root.left != null)
root = root.left;
else if (root.right != null)
root = root.right;
else
root = getNextRight(root);
}
return tempRoot;
}
// Function to get the array representation of nextRight links
List<String> printTree(Node root) {
List<String> result = new ArrayList<>();
if (root == null)
return result;
Queue<Node> q = new LinkedList<>();
q.add(root);
q.add(null);
while (!q.isEmpty()) {
Node node = q.poll();
if (node != null) {
result.add(String.valueOf(node.data));
if (node.nextRight == null) {
result.add("#");
}
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
} else if (!q.isEmpty()) {
q.add(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);
GfG tree = new GfG();
// Ensure modified root is returned
root = tree.connect(root);
List<String> output = tree.printTree(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
# Function to find the next right node
def getNextRight(p):
temp = p.nextRight
while temp is not None:
if temp.left is not None:
return temp.left
if temp.right is not None:
return temp.right
temp = temp.nextRight
return None
# Function to connect nodes at
# the same level and return root
def connect(root):
if root is None:
return None
root.nextRight = None
tempRoot = root
while root is not None:
q = root
while q is not None:
if q.left is not None:
if q.right is not None:
q.left.nextRight = q.right
else:
q.left.nextRight = getNextRight(q)
if q.right is not None:
q.right.nextRight = getNextRight(q)
q = q.nextRight
# Move to the next level starting
# with the leftmost node
if root.left is not None:
root = root.left
elif root.right is not None:
root = root.right
else:
root = getNextRight(root)
return tempRoot
# Function to get the array representation of nextRight links
def printTree(root):
result = []
if root is None:
return result
q = []
q.append(root)
q.append(None)
while len(q) > 0:
node = q.pop(0)
if node is not None:
result.append(str(node.data))
if node.nextRight is None:
result.append("#")
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
elif len(q) > 0:
q.append(None)
return result
if __name__ == "__main__":
# Constructed binary tree:
# 10
# / \
# 8 2
# /
# 3
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
# Ensure modified root is returned
root = connect(root)
output = printTree(root)
print(" ".join(output))
C#
// C# Program to Connect nodes at same level
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right, nextRight;
public Node(int val) {
data = val;
left = right = nextRight = null;
}
}
class GfG {
// Function to find the next right node
static Node getNextRight(Node p) {
Node temp = p.nextRight;
while (temp != null) {
if (temp.left != null)
return temp.left;
if (temp.right != null)
return temp.right;
temp = temp.nextRight;
}
return null;
}
// Function to connect nodes at the
// same level and return root
static Node connect(Node root) {
if (root == null)
return null;
root.nextRight = null;
Node tempRoot = root;
while (root != null) {
Node q = root;
while (q != null) {
if (q.left != null) {
if (q.right != null)
q.left.nextRight = q.right;
else
q.left.nextRight = getNextRight(q);
}
if (q.right != null)
q.right.nextRight = getNextRight(q);
q = q.nextRight;
}
// Move to the next level
// starting with the leftmost node
if (root.left != null)
root = root.left;
else if (root.right != null)
root = root.right;
else
root = getNextRight(root);
}
return tempRoot;
}
static List<string> printTree(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) {
result.Add(node.data.ToString());
if (node.nextRight == null) {
result.Add("#");
}
if (node.left != null)
queue.Enqueue(node.left);
if (node.right != null)
queue.Enqueue(node.right);
} else if (queue.Count > 0) {
queue.Enqueue(null);
}
}
return result;
}
static void Main(string[] args) {
// Constructed binary tree:
// 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);
// Ensure modified root is returned
root = connect(root);
List<string> output = printTree(root);
Console.WriteLine(string.Join(" ", output));
}
}
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;
}
}
// Function to find the next right node
function getNextRight(p) {
let temp = p.nextRight;
while (temp !== null) {
if (temp.left !== null)
return temp.left;
if (temp.right !== null)
return temp.right;
temp = temp.nextRight;
}
return null;
}
// Function to connect nodes at the same
// level and return root
function connect(root) {
if (!root) return null;
root.nextRight = null;
let tempRoot = root;
while (root !== null) {
let q = root;
while (q !== null) {
if (q.left) {
if (q.right) q.left.nextRight = q.right;
else q.left.nextRight = getNextRight(q);
}
if (q.right) q.right.nextRight = getNextRight(q);
q = q.nextRight;
}
// Move to the next level starting with
// the leftmost node
if (root.left) root = root.left;
else if (root.right) root = root.right;
else root = getNextRight(root);
}
return tempRoot;
}
// Function to store the nextRight
// pointers in level-order format
function printTree(root) {
const result = [];
if (!root) return result;
const queue = [root, null];
while (queue.length > 0) {
const node = queue.shift();
if (node !== null) {
result.push(node.data.toString());
if (node.nextRight === null) result.push("#");
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
} else if (queue.length > 0) {
queue.push(null);
}
}
return result;
}
// Constructed binary tree:
// 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);
// Ensure modified root is returned
const resRoot = connect(root);
const output = printTree(resRoot);
console.log(output.join(' '));
Time Complexity : O(n), where n is the number of nodes in a binary tree.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 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