题目大意:构造BST,输出双亲节点。

思路:新加进来的点,其父亲要么是比他大的值中最小的,或者是比他小的值中的最大的。那么后加入的那个节点就是该节点的父亲节点。
理由:

平衡二叉树的中序遍历是有序的,那么
11-2 Tree Construction

#include<iostream>
#include<vector>
#include<set>
#include<map>
using namespace std;
set<int>::iterator it;
set<int>::iterator it1;
set<int>::iterator it2;
int main()
{
    map<int,int>pos;
    int num;
    cin>>num;
    int temp;
    cin>>temp;
    set<int>res;
    res.insert(0);
    res.insert(temp);
    res.insert(1e9+1);
    pos[temp]=1;
    for(int i=2;i<=num;++i)
    {
        scanf("%d",&temp);
        it=res.lower_bound(temp);
        it1=it;
        it2=it;
        it1--;
        if(pos[*it1]>pos[*it2])
            printf("%d%c",*it1,i==num?'\n':' ');
        else
            printf("%d%c",*it2,i==num?'\n':' ');
        res.insert(temp);
        pos[temp]=i;
    }
    
}


注意:lower_bound是找出>=的最小的那个数字
upper_bound是找出>=的最小的那个数字

相关文章: