Inorder Successor in BST

PROBLEM :

Given a BST,  and a reference to a Node x the task is to find the Inorder Successor of the node .

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow.  The second line consist of an integer N. Then in the next line are N space separated values of the BST nodes. In the next line is an integer x representing the value of the node in the BST.

Output:
For each test case output will be the Inorder successor of the given node. If no such successor is present output will be -1.

Constraints:
1<=T<=100
1<=N<1100
1<=A[]<=1000

Example:
Input:
2
7
20 8 22 4 12 10 14
8
7
20 8 22 4 12 10 14
10

Output:
10
12

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*The structure of Node
struct Node {
int data;
Node * right, * left;
};*/

/* The below function should return the node which is
inorder successor of given node x. */

void FindInOrderSuccessor(Node *,Node *,Node **) ;

Node * inOrderSuccessor(Node *root, Node *x)
{
    Node * succ=NULL ;
    FindInOrderSuccessor(root,x,&succ) ;
    return succ ;
}

void FindInOrderSuccessor(Node *root,Node *x,Node **succ)
{
    if(root==NULL)
        return ;
       
    if(root==x)
    {
        if(!root->right)
            return ;
           
        Node *temp=root->right ;
        while(temp->left)
            temp=temp->left ;
           
        (*succ)=temp ;
    }
    else
    {
        if(x->data<root->data)
        {
            (*succ)=root ;
            FindInOrderSuccessor(root->left,x,&(*succ)) ;
        }
        else
            FindInOrderSuccessor(root->right,x,&(*succ)) ;
    }
}

--------------------------------------------------------------------------------

Comments

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )