×

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node.

In a Binary Search Tree, the definition of Inorder successor can be defined in another way also. It is a node which is the smallest key that is greater than the key of the input node. This is implied because in the Binary Search Tree, the Inorder traversal gives the ascending order of the elements present in the tree.

Inorder Successor in Binary Trees

The above diagram is a Binary Search Tree. So, in the above tree the Inorder successor of 3 is 5. And also the Inorder successor of 3 is 5.

In this way we can find the Inorder successor of a particular node by viewing the structure of the tree. If we know the Inorder traversal of a particular tree also we can find the Inorder successor of a particular node.

Method 1 – Using the Parent Pointer.

An assumption is that every node in the tree has a parent pointer. In this method, an algorithm is designed which is divided into two cases. This is divided based on the right sub tree of the node is empty or not empty.

In this algorithm, the particular node along with its root node is given as the input. And the Inorder successor of the provided node is given as the output.

The algorithm works on the following principles.

  1. Check if the right sub tree is NULL or not NULL.
    If it is not NULL, then the Inorder successor of that node lies in the right sub tree. It is the node in the right sub tree having the minimum key value.
  2. If the right sub tree of that node is NULL, then the Inorder successor lies between one of the ancestors. So, using the parent pointer (which is assumed that every node has a parent pointer) we should travel upwards to find the Inorder successor. We should find a node which is the left child of its corresponding parent. So, the parent node of such node becomes the Inorder successor of the provided node in the input.

Let’s implement this algorithm using JAVA programming language.

// Java program to find the Inorder successor in Binary Search Tree.
 
// A node for the binary tree is created.
class Node {
 
    int data;
    Node left, right, parent;
 
    Node (int d)
    {
        data = d;
        left = right = parent = null;
    }
}
 
class BinaryTreeDemo {
 
    static Node head;
 
    /* Given a binary search tree and a number,
     inserts a new node with the given number in
     the correct place in the tree. Returns the new
     root pointer which the caller should then use
     (The standard trick to avoid using reference
     parameters). */
    Node insert (Node new_node, int data)
    {
 
        /* 1. Check if the binary tree is empty. If yes, then return a new
      Binary tree with a single node.
*/
        if (new_node == null) {
            return (new Node (data));
        }
        else {
 
            Node temp = null;
 
            /* 2. If the tree is not empty, recur down the tree.  */
            if (data <= new_node.data) {
                temp = insert (new_node.left, data);
                new_node.left = temp;
                temp.parent = new_node;
            }
            else {
                temp = insert (new_node.right, data);
                new_node.right = temp;
                temp.parent = new_node;
            }
 
            /* return the (unchanged) node pointer */
            return new_node;
        }
    }
 
    Node inOrderSuccessor (Node root, Node n)
    {
 
        // code for the first step in the above algorithm.
        if (n.right != null) {
            return minValue (n.right);
        }
 
        // code for the second step in the above algorithm.
        Node par = n.parent;
        while (par != null && n == par.right) {
            n = par;
            par = par.parent;
        }
        return par;
    }
 
    /* Given a non-empty binary search
       tree, return the minimum data 
       value found in that tree. Note that
       the entire tree does not need
       to be searched. */
    Node minValue (Node node)
    {
        Node current_node = node;
 
        /* loop down to find the leftmost leaf */
        while (current_node.left != null) {
            current_node = current_node.left;
        }
        return current_node;
    }
 
    // Driver program to test above functions
    public static void main (String [] args)
    {
        BinaryTreeDemo tree = new BinaryTreeDemo();
        Node root = null, temp = null, suc = null, min = null;
        root = tree.insert (root, 19);
        root = tree.insert (root, 7);
        root = tree.insert (root, 21);
        root = tree.insert (root, 3);
        root = tree.insert (root, 11);
        root = tree.insert (root, 9);
        root = tree.insert (root, 13);
        temp = root.left.right.left;
        suc = tree.inOrderSuccessor (root, temp);
        if (suc != null) {
            System.out.println(
                "The Inorder successor of "
                + temp.data + "node is " + suc.data);
        }
        else {
            System.out.println(
                "Inorder successor for that node does not exist!!");
        }
    } // main
} // BinaryTreeDemo.

OUTPUT:

The Inorder successor of 9 is 11.

Let’s look into all the complexities that the above program holds.

Time Complexity of the Inorder successor program is O(h), where h is the height of the binary search tree.

Space Complexity of the Inorder successor program is O(1). As this does not require any data structure while implementing the logic.

So, in this way we can find the Inorder successor using the parent pointer.

Method 2 – Searching from the root node.

In this method the main strategy we play is searching from the root node. So, there is no need of a parent pointer. This algorithm is also divided into two stages. This division is done on the basis of the right sub tree of the given node. One stage has the input node empty and the other stage having the input node filled.

In this algorithm the root node and the node for which the Inorder successor is needed is given as the input. The Inorder successor for that particular provided node is produced as the output.

The algorithm works on the following principles.

At first, we need to check weather the right sub tree of that node is NULL or not.

  1. If it is not NULL, then the Inorder successor of that node lies in the right sub tree. It is the node in the right sub tree having the minimum key value.
  2. If the right sub tree of the node is NULL, we should use the searching technique starting from the root node. Check if the node data is greater than the root data. If yes, travel down the right sub tree. If not travel down the left sub tree.

This is the working mechanism of the above algorithm.

Let’s look the implementation of the above algorithm in java programming language.

// Java program for above approach

class BinaryTreeDemo
{
   
/* A binary tree has three parts. The data part, a pointer to the left child of the node and a pointer to the right child of the node. 
*/
static class node
{
    int data;
    node left;
    node right;
    node parent;
};
 
static node InOrderSuccessor (node root, node N)
{
     
    // First step for the above algorithm
    if (N.right != null)
        return minValue(N.right);
 
    node suc = null;
 
    // Start searching from the root node for the Inorder successor down the tree.
    while (root != null)
    {
        if (N.data < root.data)
        {
            suc = root;
            root = root.left;
        }
        else if (N.data > root.data)
            root = root.right;
        else
            break;
    }
    return suc;
}
/*
 A non-empty binary tree is given which returns the minimum data value from that binary tree. A point to be noted is that, it is not necessary for searching the whole tree.
*/ 
static node minValue (node node)
{
    node current_node = node;
 
/* 
To find the left most leaf, we should apply loop for the nodes in the binary tree.
*/
    while (current_node.left != null)
    {
        Current_node = current_node.left;
    }
    return current_node;
}
/*
This function helps in allocating the data value, null left pointer and null right pointer to the new node.
*/






static node newNode (int data)
{
    node new_node = new node ();
    new_node.data = data;
    new_node.left = null;
    new_node.right = null;
    new_node.parent = null;
 
    return (new_node);
}
/*
A binary search tree is given along with a number to insert a new node at a correct place using the number. After inserting this function returns a new root pointer which is used further in the program.
*/  
static node insert (node node, int data)
{
   
/* 1. Check if the binary tree is empty. If yes, then return a new
      Binary tree with a single node.
*/
    if (node == null)
        return (newNode(data));
    else
    {
        node temp;
 
        /* 2. If the tree is not empty, recur down the tree.  */
        if (data <= node.data)
        {
            temp = insert(node.left, data);
            node.left = temp;
            temp.parent = node;
        }
        else
        {
            temp = insert(node.right, data);
            node.right = temp;
            temp.parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
/*
 Driver code to test the above functions/ Methods 
*/
public static void main (String [] args)
{
    node root = null, temp, suc , min;
 
    // creating the binary tree.
    root = insert (root, 19);
    root = insert (root, 7);
    root = insert (root, 21);
    root = insert (root, 3);
    root = insert (root, 10);
    root = insert (root, 9);
    root = insert (root, 13);
    temp = root.left.right.left;
     
    // Function Call for the Inorder successor method.
    suc = InOrderSuccessor(root, temp);
    if (suc != null)
        System.out.printf( "\n Inorder Successor of %d is %d ",
            temp.data, suc.data);
    else
        System.out.printf("\n Inorder Successor doesn't exit");
}
}

OUTPUT:

The Inorder successor of 9 is 11.

Let’s look into all the complexities that the above program holds.

Time Complexity of the Inorder successor program is O(h), where h is the height of the binary search tree.

Space Complexity of the Inorder successor program is O(1). As this does not require any data structure while implementing the logic.

Method 3 – Inorder Traversal

Using the Inorder traversal also we can fin out the Inorder successor of a particular node. In the Inorder traversal, the first node greater than the value of current node is the Inorder traversal of the current node.

In this algorithm the root node and the node for which the Inorder successor is needed is given as the input. The Inorder successor for that particular provided node is produced as the output.

Let’s look the implementation of Inorder traversal using a java program.

// Java Program for the Inorder traversal of a Binary Search Tree
import java.util.*;
 
class InorderTraversalDemo {
 
  /*
  A binary search tree node has data, a left child pointer and a right child pointer.
     */
  static class node {
    int data;
    node left;
    node right;
    node parent;
  };
  static void InOrderTraversal(node root) {
    if (root == null) {
      return;
    }
 
    InOrderTraversal(root.left);
    System.out.print(root.data);
    InOrderTraversal(root.right);
  }
  static void InOrderTraversal(node root, node n, node suc) {
    if (root == null) {
      return;
    }
 
    InOrderTraversal(root.left, n, suc);
    if (root.data > n.data && suc.left == null) {
      suc.left = root;
      return;
    }
    InOrderTraversal(root.right, n, succ);
  }
 
  static node InOrderSuccessor(node root, node n) {
    node suc = newNode(0);
    InOrderTraversal(root, n, suc);
    return suc.left;
  }
 
  /* 
 This function helps in allocating a new node with the given data and null left and right pointers.
*/
  static node newNode(int data) {
    node node = new node ();
 
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;
 
    return (node);
  }
 
  /*
A binary search tree is given along with a number to insert a new node at a correct place using the number. After inserting this function returns a new root pointer which is used further in the program.
*/  
  static node insert (node node, int data) {
 
    /*
     1. check weather the tree is empty or not. If yes, then return the tree having the new node.
    */
    if (node == null)
      return (newNode (data));
    else {
      node temp;
 
      /* 
     2. If the root node is not empty, recur down the tree 
      */
      if (data <= node.data) {
        temp = insert (node.left, data);
        node.left = temp;
        temp.parent = node;
      } else {
        temp = insert (node.right, data);
        node.right = temp;
        temp.parent = node;
      }
 
      /* 
A node pointer which is not changed should be returned.
 */
      return node;
    }
  }
 
  // Driver code for the above approach for the binary search tree.
  public static void main (String [] args) {
    node root = null, temp, suc, min;
 
    // Creating the binary search tree by inserting these nodes.
    root = insert (root, 20);
    root = insert (root, 8);
    root = insert (root, 22);
    root = insert (root, 4);
    root = insert (root, 12);
    root = insert (root, 10);
    root = insert (root, 14);
    temp = root.left.right.left;
 
    // Function Call to get the Inorder successor of temp.
    suc = InOrderSuccessor(root, temp);
    if (suc != null)
      System.out.print("\n Inorder Successor of " + temp.data + " is " + suc.data);
    else
      System.out.print("\n Inorder Successor doesn't exist");
 
  }
}

OUTPUT:

The Inorder successor of 9 is 11.

Let’s look into all the complexities that the above program holds.

Time Complexity of the Inorder successor program is O(h), where h is the height of the binary search tree.

Space Complexity of the Inorder successor program is O(1). As it does not require any data structure while implementing the logic.

These are some of the methods to find the Inorder successor of a particular node.


Related Topics

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.

Difference between Structured and Object-Oriented Analysis

Analysis means observing and collecting relevant information about the structure of something or the basic details of a system's requirements. Structured and Object Oriented Analysis are both widely used in...

2 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Program to calculate the area of the circumcircle of an equilateral triangle

You have given one value which represents the side of the equilateral triangle. You have to find out the area of the circumcircle. Let’s take an example - For the above...

3 minutes read.