We can change the isBST () method as shown below to swap these 2 randomly changed nodes and fix them.
int isBST(struct node* node)
{
struct node *x = NULL;
return(isBSTUtil(node, INT_MIN, INT_MAX,&x));
}
int isBSTUtil(struct node* node, int min, int max, struct node **x)
{
if (node==NULL)
return 1;
if (node->data < min || node->data > max) {
if (*x == NULL) {
*x = node;
}
else {
int tmp = node->data;
node->data = (*x)->data;
(*x)->data = tmp;
}
return 1;
}
return
isBSTUtil(node->left, min, node->data-1, x) &&
isBSTUtil(node->right, node->data+1, max, x);
}
source
share