以下のようにisBST()メソッドを変更して、2つのランダムにスワップされたノードを交換して修正することができます。
/* Returns true if the given tree is a binary search tree
(efficient version). */
int isBST(struct node* node)
{
struct node *x = NULL;
return(isBSTUtil(node, INT_MIN, INT_MAX,&x));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max, struct node **x)
{
/* an empty tree is BST */
if (node==NULL)
return 1;
/* false if this node violates the min/max constraint */
if (node->data < min || node->data > max) {
if (*x == NULL) {
*x = node;//same the first incident where BST property is not followed.
}
else {
//here we second node, so swap it with *x.
int tmp = node->data;
node->data = (*x)->data;
(*x)->data = tmp;
}
//return 0;
return 1;//have to return 1; as we are not checking here if tree is BST, as we know it is not BST, and we are correcting it.
}
/* otherwise check the subtrees recursively,
tightening the min or max constraint */
return
isBSTUtil(node->left, min, node->data-1, x) && // Allow only distinct values
isBSTUtil(node->right, node->data+1, max, x); // Allow only distinct values
}
[こちら](http://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/)を参照してください。実際には3つのポインタだけを使用しています。 – user3004790