《算法笔记》9.3小节——数据结构专题(2)->树的遍历 问题 A: 树查找

题目描述

有一棵树,输出某一深度的所有节点,有则输出这些节点,无则输出EMPTY。该树是完全二叉树。

输入

输入有多组数据。

每组输入一个n(1<=n<=1000),然后将树中的这n个节点依次输入,再输入一个d代表深度。

输出

输出该树中第d层得所有节点,节点间用空格隔开,最后一个节点后没有空格。

样例输入
复制代码
5
1 2 3 4 5 
7
7
1 2 3 4 5 6 7 
2
0
样例输出
复制代码
EMPTY
2 3

分析: 由于是完全二叉树,可以用数组存储。直接找到某一层对应的编号输出即可。或者按层次分别存储。

cpp 复制代码
#include    <algorithm>
#include     <iostream>
#include      <cstdlib>
#include      <cstring>
#include       <string>
#include       <vector>
#include       <cstdio>
#include        <queue>
#include        <stack>
#include        <ctime>
#include        <cmath>
#include          <map>
#include          <set>
#include<unordered_map>
#define INF 0x3f3f3f3f
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,a) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#a<<"="<<(a)<<endl
#define db5(x,y,z,a,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#a<<"="<<(a)<<", "<<#r<<"="<<(r)<<endl
using namespace std;

int main(void)
{
    #ifdef test
    freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    clock_t start=clock();
    #endif //test

    int n;
    while(scanf("%d",&n),n)
    {
        int num[11][1026];memset(num,0,sizeof(num));
        int len[15]={0,1,2,4,8,16,32,64,128,256,512,1024};
        int index=1;
        for(int i=0;i<n;++i)
        {
            int a;scanf("%d",&a);
            if(num[index][0]<len[index])
            {
                num[index][num[index][0]+1]=a,num[index][0]++;
            }
            else
            {
                index++;
                num[index][num[index][0]+1]=a,num[index][0]++;
            }
        }
        int d;scanf("%d",&d);
        if(num[d][0]==0)printf("EMPTY\n");
        else
        {
            for(int j=1;j<=num[d][0];++j)
            {
                if(j==1)printf("%d",num[d][j]);
                else printf(" %d",num[d][j]);
            }printf("\n");
        }
    }

    #ifdef test
    clockid_t end=clock();
    double endtime=(double)(end-start)/CLOCKS_PER_SEC;
    printf("\n\n\n\n\n");
    cout<<"Total time:"<<endtime<<"s"<<endl;        //s为单位
    cout<<"Total time:"<<endtime*1000<<"ms"<<endl;    //ms为单位
    #endif //test
    return 0;
}
相关推荐
多米Domi01119 分钟前
0x3f 第49天 面向实习的八股背诵第六天 过了一遍JVM的知识点,看了相关视频讲解JVM内存,垃圾清理,买了plus,稍微看了点确定一下方向
jvm·数据结构·python·算法·leetcode
A_nanda9 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
代码雕刻家11 小时前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
Ulyanov11 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
智者知已应修善业12 小时前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
91刘仁德13 小时前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法
diediedei13 小时前
模板编译期类型检查
开发语言·c++·算法
阿杰学AI13 小时前
AI核心知识78——大语言模型之CLM(简洁且通俗易懂版)
人工智能·算法·ai·语言模型·rag·clm·语境化语言模型
mmz120713 小时前
分治算法(c++)
c++·算法
睡一觉就好了。14 小时前
快速排序——霍尔排序,前后指针排序,非递归排序
数据结构·算法·排序算法