Tree Construction CodeForces - 675D(二叉搜索树)

根据BST的特性,每次插入对应的地点都应该是唯一确定的,我们只要找出这个位置就可以了,我们发现对于一个数字k,k每次能插入的两个位置无非是①小于等于k的数中的最大值的右子树②大于k的数中的最小值的左子树。

因为插入的位置是唯一的,所以我们只要找出这两个位置中能插入的位置是那个就解决了这个问题

#include <bits/stdc++.h>
using namespace std;
set<int>set_node;
int n,k;
map<int, bool> l, r;
int main()
{
//    while(scanf("%d",&n)!=EOF)
    {
        cin >> n;
        for(int kase = 0 ; kase < n ; kase++)
        {
            scanf("%d",&k);
            if(kase != 0)
            {
                set<int>::iterator it;
                it = set_node.lower_bound(k);
                if(it != set_node.end() && l[*it] == 0)
                {
                    if(kase == 1)
                        cout << *it;
                    else
                        cout << " " << *it;
                    l[*it]++;
                }
                else
                {
                    it = set_node.upper_bound(k);
                    it--;
                    if(kase == 1)
                        cout << *it;
                    else
                        cout << " " << *it;
                    r[*it]++;
                }
            }
            set_node.insert(k);
            r[k] = l[k] = 0;
        }
        cout << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhaiqiming2010/article/details/79966512