A1064 Complete Binary Search Tree (30 分| 二叉查找树,附详细注释,逻辑分析)

写在前面
  • 思路分析
    • 给你1个序列,所有的数都非负且不同,用这个序列建一个完全二叉搜索树,再给出这个树的层序序列
    • 解题思路:
      • 二叉搜索树的中序序列是有序的,那么我们把输入的序列进行排序,得到这棵BST的中序序列
      • 再按中序遍历的方式建树,得到这棵完全二叉搜索树
      • 因为是完全二叉树,所以可以用一个数组来保存,且有n个结点,一定会把前面n个空间占满。
      • 输出层序序列
  • 热点知识,参考代码易理解
测试用例
  • input:
    10
    1 2 3 4 5 6 7 8 9 0
    output:
    6 3 8 1 5 7 9 0 2 4
    
ac代码
  • #include<iostream>
    #include<cstdio>
    #include<string>
    #include<queue>
    #include<stack>
    #include<algorithm>
    #include<cmath>
    using namespace std;
    const int maxn=1010;
    int num[maxn],cbt[maxn],n,inx=0;
    
    void inorder(int root)
    {
        if(root>n)
            return;
        inorder(2*root);
        cbt[root]=num[inx++];
        inorder(2*root+1);
    }
    
    int main()
    {
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>num[i];
        //排序得到中序序列
        sort(num,num+n);
        //按照中序序列建树
        inorder(1);
        //层序输出
        for(int i=1; i<=n; i++)
        {
            cout<<cbt[i];
            if(i<n)
                cout<<" ";
        }
        return 0;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xsimah

创作不易,感谢客官的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值