Inorder successor in Binary Tree
Last Updated :
30 Oct, 2024
Given a binary tree and a node, the task is to find the inorder successor of this node. Inorder Successor of a node in the binary tree is the next node in the Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal.
In the below diagram, inorder successor of node 4 is 2, 1 is 3 and 5 is 1.

Using Reverse Inorder - O(n) Time and O(h) Space
We do a reverse inorder traversal and keep track of the last visited node.
If we find the node and successor in the right subtree, we return it.
- If root's data is same as target, return the last visited node in the right subtree.
- Update last visited node and recur for the left subtree.
Below is the implementation of above approach:
C++
// C++ code for finding the inorder successor
// of a target value in a binary tree.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
// Function to find the inorder successor
// of a target value.
Node* getSucc(Node* root, int target, Node*& last) {
if (!root) return nullptr;
// If the target and successor are in the
// right subtree
Node* succ = getSucc(root->right, target, last);
if (succ) return succ;
// If root's data matches the target,
// return the last visited node
if (root->data == target)
return last;
// Mark the current node as
// last visited
last = root;
// Search in the left subtree
return getSucc(root->left, target, last);
}
int main() {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
int target = 4;
Node* last = nullptr;
Node* succ = getSucc(root, target, last);
if (succ)
cout << succ->data << endl;
else
cout << "null" << endl;
return 0;
}
Java
// Java code for finding the inorder successor
// of a target value in a binary tree.
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Function to find the inorder successor
// of a target value.
static Node getSucc(Node root, int target, Node[] last) {
if (root == null) return null;
// If the target and successor are in
// the right subtree
Node succ = getSucc(root.right, target, last);
if (succ != null) return succ;
// If root's data matches the target, return
// the last visited node
if (root.data == target)
return last[0];
// Mark the current node as
// last visited
last[0] = root;
// Search in the left subtree
return getSucc(root.left, target, last);
}
public static void main(String[] args) {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 4;
Node[] last = { null };
Node succ = getSucc(root, target, last);
if (succ != null)
System.out.println(succ.data);
else
System.out.println("null");
}
}
Python
# Python code for finding the inorder successor
# of a target value in a binary tree.
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to find the inorder successor
# of a target value.
def get_succ(root, target, last):
if not root:
return None
# If the target and successor are in the
# right subtree
succ = get_succ(root.right, target, last)
if succ:
return succ
# If root's data matches the target, return the
# last visited node
if root.data == target:
return last[0]
# Mark the current node as last visited
last[0] = root
# Search in the left subtree
return get_succ(root.left, target, last)
if __name__ == "__main__":
# Let's construct the binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
target = 4
last = [None]
succ = get_succ(root, target, last)
if succ:
print(succ.data)
else:
print("null")
C#
// C# code for finding the inorder successor
// of a target value in a binary tree.
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Function to find the inorder successor of
// a target value.
static Node GetSucc(Node root, int target, ref Node last) {
if (root == null) return null;
// If the target and successor are in
// the right subtree
Node succ = GetSucc(root.right, target, ref last);
if (succ != null) return succ;
// If root's data matches the target, return
// the last visited node
if (root.data == target)
return last;
// Mark the current node as last
// visited
last = root;
// Search in the left subtree
return GetSucc(root.left, target, ref last);
}
static void Main() {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 4;
Node last = null;
Node succ = GetSucc(root, target, ref last);
if (succ != null)
System.Console.WriteLine(succ.data);
else
System.Console.WriteLine("null");
}
}
JavaScript
// JavaScript code for finding the inorder successor
// of a target value in a binary tree.
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to find the inorder successor
// of a target value.
function getSucc(root, target, last) {
if (!root) return null;
// If the target and successor are in
// the right subtree
let succ = getSucc(root.right, target, last);
if (succ) return succ;
// If root's data matches the target, return
// the last visited node
if (root.data === target)
return last[0];
// Mark the current node as last visited
last[0] = root;
// Search in the left subtree
return getSucc(root.left, target, last);
}
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
let target = 4;
let last = [null];
let succ = getSucc(root, target, last);
if (succ)
console.log(succ.data);
else
console.log("null");
Using Morris Traversal - O(n) Time and O(1) Space
We can optimize the auxiliary space used using Morris Traversal (A standard technique to do inorder traversal without stack and recursion)
Below is the implementation of the above approach:
C++
// C++ code for finding the inorder successor
// of a target value in a binary tree.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
// Function to find the inorder successor of
// a target value using Morris traversal.
Node* getSucc(Node* root, int target) {
Node* curr = root;
Node* successor = nullptr;
bool targetFound = false;
while (curr != nullptr) {
if (curr->left == nullptr) {
if (targetFound) {
return curr;
}
if (curr->data == target) {
targetFound = true;
}
curr = curr->right;
} else {
// Find the inorder predecessor
// of curr
Node* pre = curr->left;
while (pre->right != nullptr
&& pre->right != curr) {
pre = pre->right;
}
if (pre->right == nullptr) {
// Make curr the right child
// of its inorder predecessor
pre->right = curr;
curr = curr->left;
} else {
// Revert the changes made in the 'if'
// part to restore the original tree
pre->right = nullptr;
if (targetFound) {
return curr;
}
if (curr->data == target) {
targetFound = true;
}
curr = curr->right;
}
}
}
// If no successor
return nullptr;
}
int main() {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
int target = 4;
Node* succ = getSucc(root, target);
if (succ)
cout << succ->data << endl;
else
cout << "NULL" << endl;
return 0;
}
C
// C code for finding the inorder successor of a
// target value in a binary tree using Morris traversal.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to find the inorder successor
// of a target value using Morris traversal.
struct Node* getSucc(struct Node* root, int target) {
struct Node* curr = root;
struct Node* successor = NULL;
int targetFound = 0;
while (curr != NULL) {
if (curr->left == NULL) {
if (targetFound) {
return curr;
}
if (curr->data == target) {
targetFound = 1;
}
curr = curr->right;
} else {
// Find the inorder predecessor of curr
struct Node* pre = curr->left;
while (pre->right != NULL
&& pre->right != curr) {
pre = pre->right;
}
if (pre->right == NULL) {
// Make curr the right child of
// its inorder predecessor
pre->right = curr;
curr = curr->left;
} else {
// Revert the changes made in the 'if'
// part to restore the original tree
pre->right = NULL;
if (targetFound) {
return curr;
}
if (curr->data == target) {
targetFound = 1;
}
curr = curr->right;
}
}
}
return NULL;
}
struct Node* createNode(int val) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
int target = 4;
struct Node* succ = getSucc(root, target);
if (succ != NULL)
printf("%d\n", succ->data);
else
printf("NULL\n");
return 0;
}
Java
// Java code for finding the inorder successor of a target
// value in a binary tree using Morris traversal.
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Function to find the inorder successor of
// a target value using Morris traversal.
static Node getSucc(Node root, int target) {
Node curr = root;
Node successor = null;
boolean targetFound = false;
while (curr != null) {
if (curr.left == null) {
if (targetFound) {
return curr;
}
if (curr.data == target) {
targetFound = true;
}
curr = curr.right;
} else {
// Find the inorder predecessor
// of curr
Node pre = curr.left;
while (pre.right != null &&
pre.right != curr) {
pre = pre.right;
}
if (pre.right == null) {
// Make curr the right child of
// its inorder predecessor
pre.right = curr;
curr = curr.left;
} else {
// Revert the changes made in the 'if'
// part to restore the original tree
pre.right = null;
if (targetFound) {
return curr;
}
if (curr.data == target) {
targetFound = true;
}
curr = curr.right;
}
}
}
// If no successor
return null;
}
public static void main(String[] args) {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 4;
Node succ = getSucc(root, target);
if (succ != null)
System.out.println(succ.data);
else
System.out.println("NULL");
}
}
Python
# Python code for finding the inorder successor of a
# target value in a binary tree using Morris traversal.
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to find the inorder successor of a
# target value using Morris traversal.
def get_succ(root, target):
curr = root
successor = None
target_found = False
while curr:
if not curr.left:
if target_found:
return curr
if curr.data == target:
target_found = True
curr = curr.right
else:
# Find the inorder predecessor of curr
pre = curr.left
while pre.right and pre.right != curr:
pre = pre.right
if not pre.right:
# Make curr the right child of
# its inorder predecessor
pre.right = curr
curr = curr.left
else:
# Revert the changes made in the 'if'
# part to restore the original tree
pre.right = None
if target_found:
return curr
if curr.data == target:
target_found = True
curr = curr.right
# If no successor
return None
if __name__ == "__main__":
# Let's construct the binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
target = 4
succ = get_succ(root, target)
if succ:
print(succ.data)
else:
print("NULL")
C#
// C# code for finding the inorder successor of a target
// value in a binary tree using Morris traversal.
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Function to find the inorder successor of a
// target value using Morris traversal.
static Node GetSucc(Node root, int target) {
Node curr = root;
bool targetFound = false;
while (curr != null) {
if (curr.left == null) {
if (targetFound) {
return curr;
}
if (curr.data == target) {
targetFound = true;
}
curr = curr.right;
} else {
// Find the inorder predecessor
// of curr
Node pre = curr.left;
while (pre.right != null && pre.right != curr) {
pre = pre.right;
}
if (pre.right == null) {
// Make curr the right child of
// its inorder predecessor
pre.right = curr;
curr = curr.left;
} else {
// Revert the changes made in the 'if'
// part to restore the original tree
pre.right = null;
if (targetFound) {
return curr;
}
if (curr.data == target) {
targetFound = true;
}
curr = curr.right;
}
}
}
// If no successor
return null;
}
static void Main() {
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 4;
Node succ = GetSucc(root, target);
if (succ != null)
System.Console.WriteLine(succ.data);
else
System.Console.WriteLine("NULL");
}
}
JavaScript
// JavaScript code for finding the inorder successor
// of a target value in a binary tree using Morris
// traversal.
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to find the inorder successor of a
// target value using Morris traversal.
function getSucc(root, target) {
let curr = root;
let successor = null;
let targetFound = false;
while (curr) {
if (!curr.left) {
if (targetFound) {
return curr;
}
if (curr.data === target) {
targetFound = true;
}
curr = curr.right;
}
else {
// Find the inorder predecessor
// of curr
let pre = curr.left;
while (pre.right && pre.right !== curr) {
pre = pre.right;
}
if (!pre.right) {
// Make curr the right child of
// its inorder predecessor
pre.right = curr;
curr = curr.left;
}
else {
// Revert the changes made in the 'if'
// part to restore the original tree
pre.right = null;
if (targetFound) {
return curr;
}
if (curr.data === target) {
targetFound = true;
}
curr = curr.right;
}
}
}
// If no successor
return null;
}
// Let's construct the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
let target = 4;
let succ = getSucc(root, target);
if (succ)
console.log(succ.data);
else
console.log("NULL");
Using BST tree properties - O(h) Time and O(1) Space
We begin traversal from root. For every node, we need to take care of 3 cases for to find its inorder successor.
- Right child of node is not NULL : . The successor will be the leftmost node in its right subtree. For example, successor for 1 is 3
- The node is the Rightmost in Tree : The successor is NULL. For example, node 6 in the above diagram.
- If right child of the node is NULL :. The successor must be an ancestor. Travel up using the parent pointer until we see a node which is left child of its parent. The parent of such a node is the successor.
Please refer to Inorder Successor in Binary Search Tree for implementation.
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