Level Order Successor of a node in Binary Tree
Last Updated :
14 Jun, 2022
Given a binary tree and a node in the binary tree, find Levelorder successor of the given node. That is, the node that appears after the given node in the level order traversal of the tree.
Note: The task is not just to print the data of the node, you have to return the complete node from the tree.
Examples:
Consider the following binary tree
20
/ \
10 26
/ \ / \
4 18 24 27
/ \
14 19
/ \
13 15
Levelorder traversal of given tree is:
20, 10, 26, 4, 18, 24, 27, 14, 19, 13, 15
Input : 24
Output : 27
Input : 4
Output : 18
Approach:
- Check if the root is NULL, that is tree is empty. If true then return NULL.
- Check if the given node is root. If true:
- Check if left child of root exists, if true return left child of root.
- Else, check if right child exists, return it.
- If the root is the only node. Return NULL.
- Otherwise, perform Level Order Traversal on the tree using a Queue.
- At every step of the level order traversal, check if the current node matches with the given node.
- If True, stop traversing any further and return the element at top of queue which will be the next node in the level order traversal.
Below is the implementation of the above approach:
C++
// CPP program to find Levelorder
// successor of given node in the
// Binary Tree
#include <bits/stdc++.h>
using namespace std;
// Tree Node
struct Node {
struct Node *left, *right;
int value;
};
// Utility function to create a
// new node with given value
struct Node* newNode(int value)
{
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->value = value;
return temp;
}
// Function to find the Level Order Successor
// of a given Node in Binary Tree
Node* levelOrderSuccessor(Node* root, Node* key)
{
// Base Case
if (root == NULL)
return NULL;
// If root equals to key
if (root == key) {
// If left child exists it will be
// the Postorder Successor
if (root->left)
return root->left;
// Else if right child exists it will be
// the Postorder Successor
else if (root->right)
return root->right;
else
return NULL; // No Successor
}
// Create an empty queue for level
// order traversal
queue<Node*> q;
// Enqueue Root
q.push(root);
while (!q.empty()) {
Node* nd = q.front();
q.pop();
if (nd->left != NULL) {
q.push(nd->left);
}
if (nd->right != NULL) {
q.push(nd->right);
}
if (nd == key)
break;
}
return q.front();
}
// Driver code
int main()
{
struct Node* root = newNode(20);
root->left = newNode(10);
root->left->left = newNode(4);
root->left->right = newNode(18);
root->right = newNode(26);
root->right->left = newNode(24);
root->right->right = newNode(27);
root->left->right->left = newNode(14);
root->left->right->left->left = newNode(13);
root->left->right->left->right = newNode(15);
root->left->right->right = newNode(19);
struct Node* key = root->right->left; // node 24
struct Node* res = levelOrderSuccessor(root, key);
if (res)
cout << "LevelOrder successor of "
<< key->value << " is " << res->value;
else
cout << "LevelOrder successor of "
<< key->value << " is " << "NULL";
return 0;
}
Java
// Java program to find Levelorder
// successor of given node in the
// Binary Tree
import java.util.*;
class GfG {
// Tree Node
static class Node {
Node left, right;
int value;
}
// Utility function to create a
// new node with given value
static Node newNode(int value)
{
Node temp = new Node();
temp.left = null;
temp.right = null;
temp.value = value;
return temp;
}
// Function to find the Level Order Successor
// of a given Node in Binary Tree
static Node levelOrderSuccessor(Node root, Node key)
{
// Base Case
if (root == null)
return null;
// If root equals to key
if (root == key) {
// If left child exists it will be
// the Postorder Successor
if (root.left != null)
return root.left;
// Else if right child exists it will be
// the Postorder Successor
else if (root.right != null)
return root.right;
else
return null; // No Successor
}
// Create an empty queue for level
// order traversal
Queue<Node> q = new LinkedList<Node> ();
// Enqueue Root
q.add(root);
while (!q.isEmpty()) {
Node nd = q.peek();
q.remove();
if (nd.left != null) {
q.add(nd.left);
}
if (nd.right != null) {
q.add(nd.right);
}
if (nd == key)
break;
}
return q.peek();
}
// Driver code
public static void main(String[] args)
{
Node root = newNode(20);
root.left = newNode(10);
root.left.left = newNode(4);
root.left.right = newNode(18);
root.right = newNode(26);
root.right.left = newNode(24);
root.right.right = newNode(27);
root.left.right.left = newNode(14);
root.left.right.left.left = newNode(13);
root.left.right.left.right = newNode(15);
root.left.right.right = newNode(19);
Node key = root.right.left; // node 24
Node res = levelOrderSuccessor(root, key);
if (res != null)
System.out.println("LevelOrder successor of "
+key.value + " is " + res.value);
else
System.out.println("LevelOrder successor of "
+key.value + " is NULL");
}
}
Python3
# Python3 program to find Level
# order successor of given node
# in the Binary Tree
# Node definition
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
# Function to find the Level
# Order Successor of a given
# Node in Binary Tree
def levelOrderSuccessor(root, key):
# Base Case
if root == None:
return None
# If root equals to key
elif root == key:
# If left child exists, it will
# be the PostOrder Successor
if root.left:
return root.left
# Else if right child exists, it
# will be the PostOrder Successor
elif root.right:
return root.right
# No Successor
else:
return None
# Create an empty queue for
# level order traversal
q = []
# Enqueue Root
q.append(root)
while len(q) != 0:
nd = q.pop(0)
if nd.left != None:
q.append(nd.left)
if nd.right != None:
q.append(nd.right)
if nd == key:
break
return q[0]
# Driver Code
if __name__ == "__main__":
root = Node(20)
root.left = Node(10)
root.left.left = Node(4)
root.left.right = Node(18)
root.right = Node(26)
root.right.left = Node(24)
root.right.right = Node(27)
root.left.right.left = Node(14)
root.left.right.left.left = Node(13)
root.left.right.left.right = Node(15)
root.left.right.right = Node(19)
key = root.right.left # node 24
res = levelOrderSuccessor(root, key)
if res:
print("LevelOrder successor of " +
str(key.value) + " is " +
str(res.value))
else:
print("LevelOrder successor of " +
str(key.value) + " is NULL")
# This code is contributed
# by Rituraj Jain
C#
// C# program to find Levelorder
// successor of given node in the
// Binary Tree
using System;
using System.Collections.Generic;
class GfG
{
// Tree Node
public class Node
{
public Node left, right;
public int value;
}
// Utility function to create a
// new node with given value
static Node newNode(int value)
{
Node temp = new Node();
temp.left = null;
temp.right = null;
temp.value = value;
return temp;
}
// Function to find the Level Order Successor
// of a given Node in Binary Tree
static Node levelOrderSuccessor(Node root, Node key)
{
// Base Case
if (root == null)
return null;
// If root equals to key
if (root == key)
{
// If left child exists it will be
// the Postorder Successor
if (root.left != null)
return root.left;
// Else if right child exists it will be
// the Postorder Successor
else if (root.right != null)
return root.right;
else
return null; // No Successor
}
// Create an empty queue for level
// order traversal
LinkedList<Node> q = new LinkedList<Node> ();
// Enqueue Root
q.AddLast(root);
while (q.Count != 0)
{
Node nd = q.First.Value;
q.RemoveFirst();
if (nd.left != null)
{
q.AddLast(nd.left);
}
if (nd.right != null)
{
q.AddLast(nd.right);
}
if (nd == key)
break;
}
return q.First.Value;
}
// Driver code
public static void Main(String[] args)
{
Node root = newNode(20);
root.left = newNode(10);
root.left.left = newNode(4);
root.left.right = newNode(18);
root.right = newNode(26);
root.right.left = newNode(24);
root.right.right = newNode(27);
root.left.right.left = newNode(14);
root.left.right.left.left = newNode(13);
root.left.right.left.right = newNode(15);
root.left.right.right = newNode(19);
Node key = root.right.left; // node 24
Node res = levelOrderSuccessor(root, key);
if (res != null)
Console.WriteLine("LevelOrder successor of "
+key.value + " is " + res.value);
else
Console.WriteLine("LevelOrder successor of "
+key.value + " is NULL");
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to find Levelorder
// successor of given node in the
// Binary Tree
// Tree Node
class Node
{
constructor(value) {
this.left = null;
this.right = null;
this.value = value;
}
}
// Utility function to create a
// new node with given value
function newNode(value)
{
let temp = new Node(value);
return temp;
}
// Function to find the Level Order Successor
// of a given Node in Binary Tree
function levelOrderSuccessor(root, key)
{
// Base Case
if (root == null)
return null;
// If root equals to key
if (root == key) {
// If left child exists it will be
// the Postorder Successor
if (root.left != null)
return root.left;
// Else if right child exists it will be
// the Postorder Successor
else if (root.right != null)
return root.right;
else
return null; // No Successor
}
// Create an empty queue for level
// order traversal
let q = [];
// Enqueue Root
q.push(root);
while (q.length > 0) {
let nd = q[0];
q.shift();
if (nd.left != null) {
q.push(nd.left);
}
if (nd.right != null) {
q.push(nd.right);
}
if (nd == key)
break;
}
return q[0];
}
let root = newNode(20);
root.left = newNode(10);
root.left.left = newNode(4);
root.left.right = newNode(18);
root.right = newNode(26);
root.right.left = newNode(24);
root.right.right = newNode(27);
root.left.right.left = newNode(14);
root.left.right.left.left = newNode(13);
root.left.right.left.right = newNode(15);
root.left.right.right = newNode(19);
let key = root.right.left; // node 24
let res = levelOrderSuccessor(root, key);
if (res != null)
document.write("LevelOrder successor of "
+key.value + " is " + res.value);
else
document.write("LevelOrder successor of "
+key.value + " is NULL");
</script>
Output: LevelOrder successor of 24 is 27
Time Complexity: O(N), as we are using a while loop which will traverse N times, where N is the number of nodes in the tree.
Auxiliary Space: O(N), as we are using extra space for the queue, which we are using for the 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