Open In App

Inorder predecessor and successor for a given key in BST | Iterative Approach

Last Updated : 27 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a BST and a key. The task is to find the inorder successor and predecessor of the given key. In case, if either of predecessor or successor is not present, then print -1.
Examples: 

Input:          50
               /  \
              /    \
            30     70
           / \     / \
          /   \   /   \
         20   40 60   80
            key = 65
Output: Predecessor : 60
        Successor : 70

Input:          50
               /  \
              /    \
            30     70
           / \     / \
          /   \   /   \
         20   40 60   80
            key = 100
Output: predecessor : 80
        successor : -1
Explanation: As no node in BST has key value greater 
than 100 so -1 is printed for successor.

In the previous post, a recursive solution has been discussed. The problem can be solved using an iterative approach. To solve the problem, the three cases while searching for the key has to be dealt with which are as described below: 

  1. Root is the given key: In this case, if the left subtree is not NULL, then predecessor is the rightmost node in left subtree and if right subtree is not NULL, then successor is the leftmost node in right subtree.
  2. Root is greater than key: In this case, the key is present in left subtree of root. So search for the key in left subtree by setting root = root->left. Note that root could be an inorder successor of given key. In case the key has no right subtree, the root will be its successor.
  3. Root is less than key: In this case, key is present in right subtree of root. So search for the key in right subtree by setting root = root->right. Note that root could be an inorder predecessor of given key. In case the key has no left subtree, the root will be its predecessor.

Below is the implementation of above approach:  

C++




// C++ program to find predecessor
// and successor in a BST
#include <bits/stdc++.h>
using namespace std;
 
// BST Node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Function that finds predecessor and successor of key in BST.
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
    if (root == NULL)
        return;
 
    // Search for given key in BST.
    while (root != NULL) {
 
        // If root is given key.
        if (root->key == key) {
 
            // the minimum value in right subtree
            // is successor.
            if (root->right) {
                suc = root->right;
                while (suc->left)
                    suc = suc->left;
            }
 
            // the maximum value in left subtree
            // is predecessor.
            if (root->left) {
                pre = root->left;
                while (pre->right)
                    pre = pre->right;
            }
 
            return;
        }
 
        // If key is greater than root, then
        // key lies in right subtree. Root
        // could be predecessor if left
        // subtree of key is null.
        else if (root->key < key) {
            pre = root;
            root = root->right;
        }
 
        // If key is smaller than root, then
        // key lies in left subtree. Root
        // could be successor if right
        // subtree of key is null.
        else {
            suc = root;
            root = root->left;
        }
    }
}
 
// A utility function to create a new BST node
Node* newNode(int item)
{
    Node* temp = new Node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A utility function to insert
// a new node with given key in BST
Node* insert(Node* node, int key)
{
    if (node == NULL)
        return newNode(key);
    if (key < node->key)
        node->left = insert(node->left, key);
    else
        node->right = insert(node->right, key);
    return node;
}
 
// Driver program to test above function
int main()
{
    int key = 65; // Key to be searched in BST
 
    /* Let us create following BST
                 50
                /  \
               /    \
              30     70
             / \     / \
            /   \   /   \
           20   40 60   80
*/
    Node* root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    Node *pre = NULL, *suc = NULL;
 
    findPreSuc(root, pre, suc, key);
    if (pre != NULL)
        cout << "Predecessor is " << pre->key << endl;
    else
        cout << "-1";
 
    if (suc != NULL)
        cout << "Successor is " << suc->key;
    else
        cout << "-1";
    return 0;
}


Java




// Java program to find predecessor
// and successor in a BST
import java.util.*;
class GFG
{
 
// BST Node
static class Node
{
    int key;
    Node left, right;
};
static Node pre;
static Node suc;
 
// Function that finds predecessor
// and successor of key in BST.
static void findPreSuc(Node root, int key)
{
    if (root == null)
        return;
 
    // Search for given key in BST.
    while (root != null)
    {
 
        // If root is given key.
        if (root.key == key)
        {
 
            // the minimum value in right subtree
            // is successor.
            if (root.right != null)
            {
                suc = root.right;
                while (suc.left != null)
                    suc = suc.left;
            }
 
            // the maximum value in left subtree
            // is predecessor.
            if (root.left != null)
            {
                pre = root.left;
                while (pre.right != null)
                    pre = pre.right;
            }
            return;
        }
 
        // If key is greater than root, then
        // key lies in right subtree. Root
        // could be predecessor if left
        // subtree of key is null.
        else if (root.key < key)
        {
            pre = root;
            root = root.right;
        }
 
        // If key is smaller than root, then
        // key lies in left subtree. Root
        // could be successor if right
        // subtree of key is null.
        else
        {
            suc = root;
            root = root.left;
        }
    }
}
 
// A utility function to create a new BST node
static Node newNode(int item)
{
    Node temp = new Node();
    temp.key = item;
    temp.left = temp.right = null;
    return temp;
}
 
// A utility function to insert
// a new node with given key in BST
static Node insert(Node node, int key)
{
    if (node == null)
        return newNode(key);
    if (key < node.key)
        node.left = insert(node.left, key);
    else
        node.right = insert(node.right, key);
    return node;
}
 
// Driver Code
public static void main(String[] args)
{
    int key = 65; // Key to be searched in BST
 
    /* Let us create following BST
                50
                / \
            / \
            30     70
            / \     / \
            / \ / \
        20 40 60 80
    */
    Node root = null;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    findPreSuc(root, key);
    if (pre != null)
        System.out.println("Predecessor is " +
                                     pre.key);
    else
        System.out.print("-1");
 
    if (suc != null)
        System.out.print("Successor is " + suc.key);
    else
        System.out.print("-1");
    }
}
 
// This code is contributed by Princi Singh


Python3




# Python3 program to find predecessor
# and successor in a BST
 
# A utility function to create a
# new BST node
class newNode:
     
    # Constructor to create a new node
    def __init__(self, data):
        self.key = data
        self.left = None
        self.right = None
         
# Function that finds predecessor and
# successor of key in BST.
def findPreSuc(root, pre, suc, key):
    if root == None:
        return
 
    # Search for given key in BST.
    while root != None:
 
        # If root is given key.
        if root.key == key:
 
            # the minimum value in right
            # subtree is predecessor.
            if root.right:
                suc[0] = root.right
                while suc[0].left:
                    suc[0] = suc[0].left
 
            # the maximum value in left
            # subtree is successor.
            if root.left:
                pre[0] = root.left
                while pre[0].right:
                    pre[0] = pre[0].right
 
            return
 
        # If key is greater than root, then
        # key lies in right subtree. Root
        # could be predecessor if left
        # subtree of key is null.
        elif root.key < key:
            pre[0] = root
            root = root.right
 
        # If key is smaller than root, then
        # key lies in left subtree. Root
        # could be successor if right
        # subtree of key is null.
        else:
            suc[0] = root
            root = root.left
 
# A utility function to insert
# a new node with given key in BST
def insert(node, key):
    if node == None:
        return newNode(key)
    if key < node.key:
        node.left = insert(node.left, key)
    else:
        node.right = insert(node.right, key)
    return node
 
# Driver Code
if __name__ == '__main__':
    key = 65 # Key to be searched in BST
 
    # Let us create following BST
    #             50
    #         / \
    #         / \
    #         30     70
    #         / \     / \
    #     / \ / \
    #     20 40 60 80
 
    root = None
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    pre, suc = [None], [None]
 
    findPreSuc(root, pre, suc, key)
    if pre[0] != None:
        print("Predecessor is", pre[0].key)
    else:
        print("-1")
 
    if suc[0] != None:
        print("Successor is", suc[0].key)
    else:
        print("-1")
 
# This code is contributed by PranchalK


C#




// C# program to find predecessor
// and successor in a BST
using System;
 
class GFG
{
 
// BST Node
class Node
{
    public int key;
    public Node left, right;
};
static Node pre;
static Node suc;
 
// Function that finds predecessor
// and successor of key in BST.
static void findPreSuc(Node root, int key)
{
    if (root == null)
        return;
 
    // Search for given key in BST.
    while (root != null)
    {
 
        // If root is given key.
        if (root.key == key)
        {
 
            // the minimum value in right subtree
            // is predecessor.
            if (root.right != null)
            {
                suc = root.right;
                while (suc.left != null)
                    suc = suc.left;
            }
 
            // the maximum value in left subtree
            // is successor.
            if (root.left != null)
            {
                pre = root.left;
                while (pre.right != null)
                    pre = pre.right;
            }
            return;
        }
 
        // If key is greater than root, then
        // key lies in right subtree. Root
        // could be predecessor if left
        // subtree of key is null.
        else if (root.key < key)
        {
            pre = root;
            root = root.right;
        }
 
        // If key is smaller than root, then
        // key lies in left subtree. Root
        // could be successor if right
        // subtree of key is null.
        else
        {
            suc = root;
            root = root.left;
        }
    }
}
 
// A utility function to create a new BST node
static Node newNode(int item)
{
    Node temp = new Node();
    temp.key = item;
    temp.left = temp.right = null;
    return temp;
}
 
// A utility function to insert
// a new node with given key in BST
static Node insert(Node node, int key)
{
    if (node == null)
        return newNode(key);
    if (key < node.key)
        node.left = insert(node.left, key);
    else
        node.right = insert(node.right, key);
    return node;
}
 
// Driver Code
public static void Main(String[] args)
{
    int key = 65; // Key to be searched in BST
 
    /* Let us create following BST
                50
                / \
            / \
            30     70
            / \     / \
            / \ / \
        20 40 60 80
    */
    Node root = null;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    findPreSuc(root, key);
    if (pre != null)
        Console.WriteLine("Predecessor is " +
                                    pre.key);
    else
        Console.Write("-1");
 
    if (suc != null)
        Console.Write("Successor is " + suc.key);
    else
        Console.Write("-1");
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript program to find predecessor
// and successor in a BST
 
  
 
// BST Node
class Node {
    constructor(val) {
        this.key = val;
        this.left = null;
        this.right = null;
    }
}
var pre;
var suc;
 
// Function that finds predecessor
// and successor of key in BST.
function findPreSuc(root , key)
{
    if (root == null)
        return;
 
    // Search for given key in BST.
    while (root != null)
    {
 
        // If root is given key.
        if (root.key == key)
        {
 
            // the minimum value in right subtree
            // is successor.
            if (root.right != null)
            {
                suc = root.right;
                while (suc.left != null)
                    suc = suc.left;
            }
 
            // the maximum value in left subtree
            // is predecessor.
            if (root.left != null)
            {
                pre = root.left;
                while (pre.right != null)
                    pre = pre.right;
            }
            return;
        }
 
        // If key is greater than root, then
        // key lies in right subtree. Root
        // could be predecessor if left
        // subtree of key is null.
        else if (root.key < key)
        {
            pre = root;
            root = root.right;
        }
 
        // If key is smaller than root, then
        // key lies in left subtree. Root
        // could be successor if right
        // subtree of key is null.
        else
        {
            suc = root;
            root = root.left;
        }
    }
}
 
// A utility function to create a new BST node
function newNode(item)
{
    var temp = new Node();
    temp.key = item;
    temp.left = temp.right = null;
    return temp;
}
 
// A utility function to insert
// a new node with given key in BST
function insert(node , key)
{
    if (node == null)
        return newNode(key);
    if (key < node.key)
        node.left = insert(node.left, key);
    else
        node.right = insert(node.right, key);
    return node;
}
 
// Driver Code
 
 
    var key = 65; // Key to be searched in BST
 
    /* Let us create following BST
                50
                / \
            / \
            30     70
            / \     / \
            / \ / \
        20 40 60 80
    */
    var root = null;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    findPreSuc(root, key);
    if (pre != null)
        document.write("Predecessor is " +
                                     pre.key+"<br/>");
    else
        document.write("-1<br/>");
 
    if (suc != null)
        document.write("Successor is " + suc.key);
    else
        document.write("-1");
 
// This code contributed by gauravrajput1
 
</script>


Output: 

Predecessor is 60
Successor is 70

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
Related Article: https://www.geeksforgeeks.org/inorder-predecessor-successor-given-key-bst/



Similar Reads

Inorder predecessor and successor for a given key in BST
There is BST given with root node with key part as integer only. The structure of each node is as follows: C/C++ Code struct Node { int key; struct Node *left, *right ; }; Java Code static class Node { int key; Node left, right ; }; // This code is contributed by gauravrajput1 C/C++ Code class Node: def __init__(self, key): self.key = key self.left
26 min read
Replace each node in binary tree with the sum of its inorder predecessor and successor
Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 11 / \ 9 13 / \ / \ 2 3 4 3 For 1: Inorder predecessor = 5 Inorder successor = 6 Sum = 11 For 4: Inorder predecessor = 0 (as inorder predec
20 min read
Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
Given a binary tree consisting of N nodes, the task is to replace each node in the binary tree with the sum of its preorder predecessor and preorder successor. Examples: Input: 2 / \ 3 4 / \ / \ 6 5 7 8 Output: 3 / \ 8 12 / \ / \ 8 10 12 7 Explanation: For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor
13 min read
Van Emde Boas Tree - Set 3 | Successor and Predecessor
It is highly recommended to read the previous articles on Van Emde Boas Tree first. Procedure for successor: Base case: If the size of the tree is 2 then if query-key is 0 and key - 1 is present in the tree then return 1, as it will be the successor. Otherwise, return null.If the key is less than minimum then we can easily say that minimum will be
23 min read
Proto Van Emde Boas Tree | Set 6 | Query : Successor and Predecessor
Please refer all previous articles on Proto Van Emde Boas Tree first.Successor Query Procedure: Base case: For Proto-VEB of size 2 the only possibility is that key is 0 and if the next key is present then it is its successor or there is no successor. So the same procedure is applied.Recursion: First, we will look in the present cluster (means the c
19 min read
Inorder Successor in Binary Search Tree
In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal. In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key greater than the key of the input node. So, it is sometimes important
45 min read
Populate Inorder Successor for all nodes
Given a Binary Tree where each node has the following structure, write a function to populate the next pointer for all nodes. The next pointer for every node should be set to point to in-order successor. C/C++ Code class node { public: int data; node* left; node* right; node* next; }; // This code is contributed // by Shubham Singh C/C++ Code struc
8 min read
Inorder Successor of a node in Binary Tree
Given a binary tree and a node, we need to write a program to find inorder successor of this node.Inorder Successor of a node in binary tree is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal. In the above diagram, inorder successor of node 4 is 2 and node 5 is 1. We have alrea
17 min read
Largest number less than or equal to N in BST (Iterative Approach)
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: For the above given binary search tree- Input : N = 24 Output :result = 21 (searching for 24 will be like-5-&gt;12-&gt;21) Input : N
7 min read
Smallest number in BST which is greater than or equal to N ( Iterative Approach)
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Examples: Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST
8 min read