Find an inorder successor in BST without extra space

I am looking for a way to find a successor node in BST without using extra space.

+5
source share
4 answers

To get the successor inorder of this node N, we use the following rules:

  • If it Nhas the correct child R, then inorderSuccessor(N)the left-most decedent R.
  • Else inorderSuccessor(N)is closest ancestor M, N(if it exists) such that Noriginates from a left child device M. If there is no such ancestor, inorderSucessor does not exist.

Consider the sample tree:

     A
    / \
   B   C
  / \ 
 D   E
    /
   F

Whose bypass gives in order: D B F E A C

inorderSuccessor(A)= C, C - A.

inorderSuccessor(B)= F F - B.

inorderSuccessor(C)= .

inorderSuccessor(D)= B B D.

inorderSuccessor(E)= A. E , 2. E, B, E B, B A B A, A .

inorderSuccessor(F)= E F E.

:

treeNodePtr inorderSucessor(treeNodePtr N) {
        if(N) {
                treeNodePtr tmp;
                // CASE 1: right child of N exists.
                if(N->right) {
                        tmp = N->right;
                        // find leftmost node.
                        while(tmp->left) {
                                tmp = tmp->left;
                        }
                // CASE 2: No right child.
                } else {
                        // keep climbing till you find a parent such that
                        // node is the left decedent of it.
                        while((tmp = N->parent)) {
                                if(tmp->left == N) {
                                        break;
                                }
                                N = tmp;
                        }
                }
                return tmp;
        }
        // No IOS.
        return NULL;
}

+11

NODE

struct node * inOrderSuccessor(struct node *root, struct node *n)
   { 
   //*If the node has a right child, return the smallest value of the right sub tree*

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

   //*Return the first ancestor in whose left subtree, node n lies*
   struct node *succ=NULL;
   while(root) 
   { 
      if(n->datadata < root->data) 
         {
            succ=root; root=root->left; 
         }

      else if(n->data > root->data) 
         root=root->right; 
      else break; 
   } 
  return succ;
 }

, . , . .

+5

node - , , node N . N.

, , node - . .

Node InOrderSuccessor(Node node) {
    if (node.right() != null) {
        node = node.right()
        while (node.left() != null) 
            node = node.left()
        return node
    } else {
        parent = node.getParent();
        while (parent != null && parent.right() == node) {
            node = parent
            parent = node.getParent()
        }
        return parent
    }
}
+3

node, , . . .

+1

All Articles