Codeforces 675D Tree Construction【构造,BST】

本文介绍了一个Codeforces竞赛中的难题,涉及使用二叉树解决寻找子节点父节点的问题。通过分析二叉树的性质,作者提出了一种高效的方法来确定每个节点的父节点,特别是当节点的儿子节点为空时的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值