二叉排序树

二叉排序树裸题。

牛客网补充说明:输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。

所以建立的二叉排序树中不包含重复元素。

const int N=110;
int a[N];
PII tree[N];
int n;

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

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

void preorder(int root)
{
    if(root == -1) return;
    cout<<a[root]<<' ';
    preorder(tree[root].fi);
    preorder(tree[root].se);
}

void inorder(int root)
{
    if(root == -1) return;
    inorder(tree[root].fi);
    cout<<a[root]<<' ';
    inorder(tree[root].se);
}

void postorder(int root)
{
    if(root == -1) return;
    postorder(tree[root].fi);
    postorder(tree[root].se);
    cout<<a[root]<<' ';
}

int main()
{
    while(cin>>n)
    {
        for(int i=0;i<n;i++) cin>>a[i];

        int root=-1;
        for(int i=0;i<n;i++)
            insert(root,i);

        preorder(root);
        cout<<endl;
        inorder(root);
        cout<<endl;
        postorder(root);
        cout<<endl;
    }

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