The order of a Tree hdu3999 二叉搜索树

题目链接:
hdu3999 The order of a Tree

题意:
给一个二叉搜索树的序列,求输出可以构成这个二叉搜索树的且满足字典序最小的插入序列
找了一个比较具体描述怎么根据序列建立二叉搜索树的
图片来自:https://blog.csdn.net/qq_39290830/article/details/85197994
在这里插入图片描述

思路:
首先,根据输入键的顺序,构造对应的二叉搜索树;然后,前序遍历这棵二叉树,得出的
树的顺序就是以最小的字典序生成的相同形状的树。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <sstream>

using namespace std;

typedef long long ll;

const int inf = 0x3f3f3f3f;
const int maxn = 1000005;

struct Treenode
{
    int data;
    Treenode *lch, *rch;
};


int arr[maxn],cnt;

Treenode *Creat(Treenode *rt,int val)
{
    if(rt == NULL){
        rt = new Treenode;
        rt->data = val;
        rt->lch = rt->rch = NULL;
        return rt;
    }
    //保证小的都是靠左边的
    if(rt->data > val){
        rt->lch = Creat(rt->lch,val);
    }
    //保证靠右半部分的都是较大的数
    else{
        rt->rch = Creat(rt->rch,val);
    }
    return rt;
}

void for_order(Treenode *rt)
{
    if(rt == NULL){
        return ;
    }
    arr[cnt] = rt->data;
    cnt++;
    for_order(rt->lch);
    for_order(rt->rch);
}

int main()
{
    int n;
    cin>>n;
    Treenode *rt = NULL;
    while(n--){
        int val;
        cin>>val;
        rt = Creat(rt,val);
    }
    for_order(rt);
    for(int i = 0; i < cnt - 1; i++){
        cout<<arr[i]<<' ';
    }
    cout<<arr[cnt - 1]<<endl;
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值