二叉搜索树

在二叉搜索树中,中序遍历的结果总是所有元素的升序排列(如上表中标红的一行所示);换句话说,中序遍历结果是不能帮助我们判断两个序列是否对应同一棵二叉搜索树的。这是其他几种遍历无法做到的。

而层序、先序、后序遍历都可以用来判断两个给定序列是否为同一棵二叉搜索树。

const int N=110;
string s;
PII tree[N];
vector<char> pre,temp;
int n;

void insert(int &root,int idx)
{
    if(root == -1)
    {
        root=idx;
        tree[root]={-1,-1};
        return;
    }

    if(s[idx] < s[root])
        insert(tree[root].fi,idx);
    else
        insert(tree[root].se,idx);
}

void preorder(int root,vector<char> &pre)
{
    if(root == -1) return;
    pre.pb(s[root]);
    preorder(tree[root].fi,pre);
    preorder(tree[root].se,pre);
}

int main()
{
    while(cin>>n && n)
    {
        cin>>s;

        int root=-1;
        for(int i=0;i<s.size();i++)
            insert(root,i);
        
        pre.clear();
        preorder(root,pre);

        for(int i=0;i<n;i++)
        {
            cin>>s;
            root=-1;
            for(int j=0;j<s.size();j++)
                insert(root,j);

            temp.clear();
            preorder(root,temp);

            if(temp == pre) puts("YES");
            else puts("NO");
        }
    }

    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14448800.html