1

I'm using a BST. Given a specific node, how do I find the immediate larger element in the tree?

  • Is your question specific to a c++ code ? (since you flagged it). In this case, please provide a minimal code, your exact issue and what you tried. If your question is more general, the answer is in understanding what a BST is. – Michael Doubez Oct 30 '19 at 22:09

1 Answers1

0

So basically you want the inorder successor of the given node: Below is the solution:

struct node * inOrderSuccessor(struct node *root, struct node *n) 
{ 

    if( n->right != NULL ) 
        return minValue(n->right); 

    struct node *succ = NULL; 

    // Start from root and search for successor down the tree 
    while (root != NULL) 
    { 
        if (n->data < root->data) 
        { 
            succ = root; 
            root = root->left; 
        } 
        else if (n->data > root->data) 
            root = root->right; 
        else
           break; 
    } 

    return succ; 
} 

Logic of the algorithm is (it does not require parent node pointer):

1) If right subtree of node is not NULL, then succ lies in right subtree. Do following. Go to right subtree and return the node with minimum key value in right subtree.

2) If right subtree of node is NULL, then start from root and use search like technique. Do following. Travel down the tree, if a node’s data is greater than root’s data then go right side, otherwise go to left side.

ashwin agrawal
  • 1,603
  • 8
  • 16