Open In App

Inorder successor in Binary Tree

Last Updated : 30 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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");

Output
2

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");

Output
2

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads