Codeforces 675D Tree Construction【构造,BST】

题目链接:

http://codeforces.com/contest/675/problem/D

题意:

给定数列,依次插入二叉树,求子节点的父节点。

分析:

根据二叉树的性质,我们可以找到大于这个数的最小值和小于这个数的最大值,这两个数即为该数的父节点,那么如果结点对应的儿子结点为空,直接放进去即可。注意由于这两个数的性质不存在两个结点都没有空的子节点的情况。

代码:

/*
On a hill is a tree, on a tree is a bough;
My heart for the Lord, but he never knows.

--Created by jiangyuzhu
--2016/5/17
*/
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<stack>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
using namespace std;
#define pr(x) cout << #x << ": " << x << "  "
#define pl(x) cout << #x << ": " << x << endl;
#define sa(x) scanf("%d",&(x))
#define sal(x) scanf("%I64d",&(x))
#define mdzz cout<<"mdzz"<<endl;
typedef long long ll;
const int maxn = 1e5 + 5, mod = 1e9 + 7;
int a[maxn];
map<int, int> lson, rson;
int main(void)
{
   int n;sa(n);
   set<int>s;
   int x;
   set<int>::iterator pos;
   for(int i = 0; i < n; i++){
        scanf("%d", &x);
        if(i == 0){
            s.insert(x);
            continue;
        }
        pos = s.lower_bound(x);
        if(pos != s.end() && lson[*pos]== 0 ){
            lson[*pos] = x;

        }else{
            pos--;
            rson[*pos] = x;
        }
        printf("%d ", *pos);
        s.insert(x);
   }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值