HDU 3999 BST + 先序遍历

来源:互联网 发布:阿里云怎么升级配置 编辑:程序博客网 时间:2024/05/22 08:05

传送门:HDU 3999

题意

给出一组数, 按照bst树构建, 输出字典序最小得可构成相同bst树的序列


二分查找树

转载BST

题解

BST构建, 根据bst树的特性, 构造时只要先插入中间结点就可确定树的形状
ex: 构造树2, 3, 1按2, 1, 3次序输入是相同的结果
所以先构造然后树的先序遍历输出即可


AC code:

/*adrui's submissionLanguage : C++Result : AcceptedLove : yyFavorite : Dragon BallsStanding in the Hall of Fame*/#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#include<iostream>#include<bitset>#include<map>#include<cctype>using namespace std;#define M(a, b) memset(a, b, sizeof(a))#define mid ((l + r) >> 1)#define ls rt << 1, l, mid#define rs rt << 1|1, mid + 1, r#define lowbit(x) (x & (-x))#define LL long long#define REP(n) for(int i = 0; i < n; i++)#define debug 0const int maxn(4000005);                                                //最大节点数int n, cnt;struct BST {    BST *lch, *rch;    int key;    BST(int key = 0) {        this->key = key;        lch = rch = NULL;    }    void preorder() {        if (cnt++) cout << " ";        cout << key;        if (lch != NULL) lch->preorder();        if (rch != NULL) rch->preorder();    }    void insert(int key) {        BST *rt = this, *tmp = new BST(key);        while (rt->key) {            if (tmp->key < rt->key) {                if (rt->lch == 0)                    rt->lch = new BST;                rt = rt->lch;            }            else {                if (rt->rch == 0)                    rt->rch = new BST;                rt = rt->rch;            }        }        rt->key = tmp->key;    }};int main() {#if debug    freopen("in.txt", "r", stdin);#endif //debug    cin.tie(0);    cin.sync_with_stdio(false);    int a;    while (cin >> n) {        BST rt;        cnt = 0;        for (int i = 0; i < n; ++i) {            cin >> a;            rt.insert(a);        }        rt.preorder();        cout << endl;    }    return 0;}
0 0
原创粉丝点击