Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST.
1. The swapped nodes are not adjacent in the inorder traversal of the BST.
2. The swapped nodes are adjacent in the inorder traversal of BST.
Read full article from Two nodes of a BST are swapped, correct the BST | GeeksforGeeks
1. The swapped nodes are not adjacent in the inorder traversal of the BST.
2. The swapped nodes are adjacent in the inorder traversal of BST.
// This function does inorder traversal to find out the two swapped nodes.// It sets three pointers, first, middle and last. If the swapped nodes are// adjacent to each other, then first and middle contain the resultant nodes// Else, first and last contain the resultant nodesvoid correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ){ if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); }}void correctBST( struct node* root ){ // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the poiters to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST.}
No comments:
Post a Comment