Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Predecessor And Successor In BST

Easy
0/40
Average time to solve is 10m
profile
Contributed by
135 upvotes
Asked in companies
AdobeD.E.Shaw

Problem statement

You have been given a binary search tree of integers with ‘N’ nodes. You are also given 'KEY' which represents data of a node of this tree.


Your task is to return the predecessor and successor of the given node in the BST.


Note:
1. The predecessor of a node in BST is that node that will be visited just before the given node in the inorder traversal of the tree. If the given node is visited first in the inorder traversal, then its predecessor is NULL.

2. The successor of a node in BST is that node that will be visited immediately after the given node in the inorder traversal of the tree. If the given node is visited last in the inorder traversal, then its successor is NULL.

3. The node for which the predecessor and successor will not always be present. If not present, you can hypothetically assume it's position (Given that it is a BST) and accordingly find out the predecessor and successor.

4. A binary search tree (BST) is a binary tree data structure which has the following properties.
     • The left subtree of a node contains only nodes with data less than the node’s data.
     • The right subtree of a node contains only nodes with data greater than the node’s data.
     • Both the left and right subtrees must also be binary search trees.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains the elements of the tree in the level order form separated by a single space. If any node does not have a left or right child, take -1 in its place. Refer to the example for further clarification.

The second line contains 'KEY' representing the data of the node for which the predecessor and successor are to be found.
Example:
Elements are in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.

For example, the input for the tree depicted in the below image would be :

Example

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :
Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. 

The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

The input ends when all nodes at the last level are null (-1).
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 

The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output Format :
The only line contains two single space-separated integers representing data values of the predecessor and the successor node, respectively. If any of the two doesn’t exist, print -1 in place of it.
Note:
You are not required to print anything explicitly. It has already been taken care of. Just implement the function.
Sample Input 1:
15 10 20 8 12 16 25 -1 -1 -1 -1 -1 -1 -1 -1
10
Sample output 1:
8 12
Explanation of Sample output 1:
The tree can be represented as follows:

Example

The inorder traversal of this tree will be 8 10 12 15 16 20 25.

Since the node with data 8 is on the immediate left of the node with data 10 in the inorder traversal, the node with data 8 is the predecessor.

Since the node with data 12 is on the immediate right of the node with data 10 in the inorder traversal, the node with data 12 is the successor.
Sample Input 2:
10 5 -1 -1 -1
5
Sample output 2:
-1 10
Constraint :
1 <= N <= 10^4
1 <= data <= 10^7

Time Limit: 1 sec
Hint

Store the nodes in the order of inorder traversal.

Approaches (2)
INORDER TRAVERSAL
  • The fact that all the data values are unique makes the solution look very intuitive.
  • We can simply store the inorder traversal of the given tree in the array, and find the element present before and after the given node in the array.
    • For every node, its left subtree is visited recursively, and then the node itself is visited(the data is stored in the array), and then its right subtree.
  • After the traversal, we can find the given node in the inorder array and return its predecessor and successor, if any.
Time Complexity

O(N),  where ‘N’ is the number of nodes in the BST.

 

As we are traversing each node of the BST once, the time complexity will be linear.

Space Complexity

O(N), where ‘N’ is the number of nodes in the BST.

 

In the worst case (skewed trees), we will have all the nodes of the BST in the recursion stack. 

Also, the maximum possible size of the array used to store inorder traversal will be equal to N. Hence, the space complexity is linear.

Code Solution
(100% EXP penalty)
Predecessor And Successor In BST
All tags
Sort by
Search icon

Interview problems

Python

def predecessorSuccessor(root, key):

    pred=-1

    succ=-1

 

    def Predecessor(node):

        if node is None:

            return None

        while node.right:

            node=node.right

        return node.data

 

    def Successor(node):

        if node is None:

            return None

        while node.left:

            node=node.left

        return node.data

 

    curr=root

    while curr:

        if curr.data == key:

            if curr.left:

                pred=Predecessor(curr.left)

            if curr.right:

                succ=Successor(curr.right)

            break

        elif curr.data > key:

            succ=curr.data

            curr=curr.left

        else:

            pred=curr.data

            curr=curr.right

    return [pred,succ]

20 views
0 replies
0 upvotes

Interview problems

Predecessor And Successor In BST using binary search

void inorder(TreeNode *root,vector<int>&v)

{

    if(root==NULL)

    {

        return;

    }

    inorder(root->left,v);

    v.push_back(root->data);

    inorder(root->right,v);

}

 

pair<int, int> predecessorSuccessor(TreeNode *root, int key)

{

    // Write your code here.

    vector<int>v;

    

    inorder(root,v);

    int s=0;

    int e=v.size()-1;

    

    int mid;

    while(s<=e)

    {

         if(v[0]==key)

      {

        

          return make_pair(-1,v[1]);

      }

      if(v[0]>key)

      {

          return make_pair(-1,v[0]);

      }

       if(v[e]==key)

      {

       

          return make_pair(v[e-1],-1);

      }

      if(v[e]<key)

      {

           return make_pair(v[e],-1);

      }

        mid=s+(e-s)/2;

      if(v[mid]==key)

      {

         return make_pair(v[mid-1],v[mid+1]);

          

      }

      if(v[mid]<key)

      {

          s=mid+1;

      }

if(v[mid]<key && v[mid+1]>key)

{

    return make_pair(v[mid],v[mid+1]);

}

      if(v[mid]>key)

      {

          e=mid-1;

      }

      if(v[mid]>key && v[mid-1]<key)

{

    return make_pair(v[mid-1],v[mid]);

}

 

     

    }

   

}

146 views
1 reply
1 upvote

Interview problems

Easy C++ solution to pass all test case

 

pair<int, int> predecessorSuccessor(TreeNode *root, int key)

{

    // Write your code here.

      if(root == NULL){

 

        pair<int , int> p = make_pair(NULL , NULL);

 

        return p;

 

    }

    

    int pred = -1;

    int succ = -1;

    

    TreeNode* temp = root;

    while(temp != NULL){

 

        if(temp -> data > key){

            succ = temp -> data;

            temp = temp -> left;

        }

        else if(temp -> data == key){

            break;

        }

        else{

            pred = temp -> data;

            temp = temp -> right;

        }

    }

 

    if(temp == NULL){

        return make_pair(pred, succ);

    }

 

    TreeNode* leftNode = temp -> left;

    while(leftNode != NULL){

        pred = leftNode -> data;

        leftNode = leftNode -> right;

    }

 

    TreeNode* rightNode = temp -> right;

    while(rightNode != NULL){

        succ = rightNode -> data;

        rightNode = rightNode -> left;

    }

 

    return make_pair(pred, succ);

 

}

284 views
0 replies
2 upvotes

Interview problems

Wrong Test Case

6521171 5650934 9278816 899375 -1 8989449 -1 -1 -1 -1 -1  9615950 *9615950 is not present in BST

83 views
1 reply
3 upvotes

Interview problems

My Approach : ) { T.C. :- O(n) S.C. :- O(n) }

/*************************************************************


 

    Following is the Binary Tree node structure

    class TreeNode

    {

    public:

        int data;

        TreeNode *left, *right;

        TreeNode() : data(0), left(NULL), right(NULL) {}

        TreeNode(int x) : data(x), left(NULL), right(NULL) {}

        TreeNode(int x, TreeNode *left, TreeNode *right) : data(x), left(left), right(right) {}

    };


 

*************************************************************/

TreeNode* insert_into_tree(TreeNode* &root, int key, bool &flag){

    if(root == NULL && flag == 0){

        TreeNode* temp = new TreeNode(key);

        return temp;

    }


 

    if(root->data == key && flag == 0){

        flag = 1;

        return root;

    }


 

    if(root->data > key && flag == 0){

        root->left = insert_into_tree(root->left, key, flag);

    }


 

    if(root->data < key && flag == 0){

        root->right = insert_into_tree(root->right, key, flag);

    }


 

    return root; // forgot this before...!! (took too much time/ frustated me !!  [ :( ])  (remember this from next time please...)

}


 

void inorder(TreeNode* root, vector<int> &v){

    if(root == NULL){

        return;

    }

    inorder(root->left, v);

    v.push_back(root->data);

    inorder(root->right, v);

}


 

int binary_search(int key, vector<int> &v){

    int s = 0, e = v.size()-1;

    int mid = s + (e-s)/2;


 

    while(s <= e){

        if(v[mid] == key){

            return mid;

        }

        else if(v[mid] < key){

            s = mid+1;

        }

        else{ // v[mid] > key

            e = mid-1;

        }

        mid = s + (e-s)/2;

    }

    return -1;

}


 

pair<int, int> predecessorSuccessor(TreeNode *root, int key)

{

    // Write your code here.

    bool flag = 0;

    insert_into_tree(root, key, flag);


 

    vector<int> v; // will be sorted


 

    inorder(root, v);


 

    int index = binary_search(key, v);


 

    pair<int, int> p;

    if(v.size() == 1){

        p.first = -1;

        p.second = -1;

    }

    else if(index == 0 && v.size() > 1){

        p.first = -1;

        p.second = v[1];

    }

    else if(index == v.size()-1 && v.size() > 1){

        p.first = v[v.size()-2];

        p.second = -1;

    }

    else{

        p.first = v[index-1];

        p.second = v[index+1];

    }

    return p;

}

122 views
0 replies
0 upvotes

Interview problems

C++ ,T.C = O(n) , S.C = O(1);

int min_value(TreeNode *root){

  TreeNode *temp = root;

 

  while(temp->left!=NULL){

    temp=temp->left;

  }

  return temp->data;

}

int max_value(TreeNode *root){

  TreeNode *temp = root;

 

  while(temp->right!=NULL){

    temp=temp->right;

  }

  return temp->data;

}

 

pair<int, int> predecessorSuccessor(TreeNode *root, int key)

{

    // Write your code here.

    pair<int,int> answer;

    answer.first = -1;

    answer.second =-1;

    TreeNode *temp = root;

    while(temp != NULL && temp->data != key){

      if(temp->data > key){

        answer.second=temp->data;

        temp=temp->left;

      }

      else{

        answer.first=temp->data;

        temp=temp->right;

      }

    }

    if (temp == NULL) {

        // Key not found in the tree

        return answer;

    }

 

    if (temp->left != NULL) {

        answer.first = max_value(temp->left);

    }

    if (temp->right != NULL) {

        answer.second = min_value(temp->right);

    }

    return answer;

}

166 views
0 replies
1 upvote

Interview problems

question jala do not found ka meaning ni aata

testcase 3 

44 views
0 replies
2 upvotes

Interview problems

Easy to understand CPP solution.

This solution is easy to understand but it's not the best of the solutions. The problem statement in this question is not properly defined , there exists cases where the key itself is not present in the tree. Solution : 

 

pair<int, int> predecessorSuccessor(TreeNode *root, int key)

{

    // Write your code here.

    if(root == NULL){

        pair<int , int> p = make_pair(NULL , NULL);

        return p;

    }

 

    int pred =-1;

    int succ = -1;

 

    TreeNode* temp = root;

    while(temp!=NULL){

    if(key>temp->data ){

        pred = temp->data;

        temp = temp->right;

    }

    else if(key<temp->data){

        succ =temp->data;

        temp = temp->left;

    }

    else if(key==temp->data){

        break;

    }

    }

 

    if(temp==NULL){

        return make_pair(pred,succ);

    }

    

    TreeNode* leftTree = temp->left;

    TreeNode* rightTree = temp->right;

 

    while(leftTree!=NULL){

        pred = leftTree->data;

        leftTree = leftTree->right;

    }

 

    while(rightTree!=NULL){

        succ = rightTree->data;

        rightTree = rightTree->left;

    }

 

    return make_pair(pred,succ);

 

}

432 views
1 reply
0 upvotes

Interview problems

Solution Of Problem With TestCases:

Actually Problem is not with TestCases, Problem Statement Is Not Defined Properly,

 

Here You Will Not Get Key Everytime In BST and in the case where you do not find it, you need to return predecessor and successor of nearest value to that key,just like ceil and floor of a number

 

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Solution {
    public static List<Integer> ps(TreeNode root,int key,List<Integer>ans){
        if(root==null) return ans;
        if(root.data==key){
            if(root.left!=null){
                ans.set(0,root.left.data);
            }
            if(root.right!=null){
                ans.set(1,root.right.data);
            }
            return ans;
        }
        if(root.data>key){
            if(ans.get(1)>root.data || ans.get(1)==-1) ans.set(1,root.data);
            return ps(root.left, key, ans);
        }
        if(root.data<key){
            if(ans.get(0)<root.data || ans.get(0)==-1) ans.set(0,root.data);
            return ps(root.right, key, ans);
        }
        return ans;
    }
    public static List<Integer> predecessorSuccessor(TreeNode root, int key) {
        List<Integer>ans=new ArrayList<>();
        ans.add(-1);
        ans.add(-1);
        return ps(root,key,ans);
    }
}
199 views
0 replies
0 upvotes

Interview problems

Most Optimized Java Solution T.C O(h)

import java.util.*;

public class Solution {
    public static List<Integer> predecessorSuccessor(TreeNode root, int key) {
        TreeNode successor = null;
        TreeNode predcessor = null;

        TreeNode node = root;

        while (node != null) {
            // System.out.println(node.data);
            if(node.data > key){
                successor = node;
                node = node.left;
            }else{
                node = node.right;
            }
        }

        node = root;
        // System.out.println("-------");
        while (node != null) {
            // System.out.println(node.data);
            if(node.data >=key){
                node = node.left;
            }else{
                predcessor = node;
                node = node.right;
                // break;
            }
        }

        List<Integer> ans = new ArrayList<>();
        ans.add((predcessor == null ? -1 : predcessor.data));
        ans.add(successor == null ? -1 : successor.data);
        return ans;
        
    }
}

java

115 views
0 replies
1 upvote
Full screen
Console