二叉搜索树,如果正确采取中序遍历,将是一个递增的序列。
例如正确的中序情况:1 2 3 4 5
那么交换其中任意两个节点情况:

可以发现,其本质是寻找逆序对,可能只有一组1 3 2 4 5
可能有两组:1 5 3 4 2 或 1 4 3 2 5

那么只需要中序遍历二叉树,找到逆序对,第一个数,最后一个数

#include<iostream>
#include<vector>
#include<stack>
using namespace std;
int main()
{
    int n,root;
    cin>>n>>root;
    vector<int> l(n+1,0);
    vector<int> r(n+1,0);
    for(int i=0;i<n;i++)
    {
        int fa,lc,rc;
        cin>>fa>>lc>>rc;
        l[fa]=lc;
        r[fa]=rc; 
    }
    int error1=0;
    int error2=0;//记录下错误节点
    stack<int> stk;
    int p=root;
    int pre=0;
    while(stk.empty()==false || p!=0) 
    {
        if(p!=0) //当前研究节点
        {
            stk.push(p);//入栈
            p=l[p];//移动到左边节点
        }
        else
        {
            int top=stk.top();
            stk.pop();
            if(top<pre)  //找到一组逆序对
            {
                if(error1==0)
                    error1=pre;
                error2=top;
            }
            pre=top;//填充pre
            p=r[top];//  转移到右子树
        }
    }
    if(error1<error2)
        cout<<error1<<" "<<error2<<endl;
    else
        cout<<error2<<" "<<error1<<endl;
}