• 完全二叉树


    题目描述

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

    输入描述:

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

    输出描述:

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

    分析

    用数组存储完全二叉树的结点数据,然后根据完全二叉树的性质找出第d层结点并输出

    #include <iostream>
    #include <math.h>
    using namespace std;
    
    int main(){
        int n, d;
        int a[1000];
        while(cin >> n){
        	for(int i = 1; i <= n; i++){
        		cin >> a[i];
        	}
        	cin >> d;
        	int count1 = pow(2, d - 1) - 1;
        	int count2 = pow(2, d) - 1 - count1;
        	if(n > count1 && n <= count2){
        		for(int i = count1+1; i < n; i++){
        			cout << a[i] << " ";
        		}
        		cout << a[n] << endl;
        	}
        	else if(n > count2){
        		for(int i = count1 + 1; i < count1 + count2; i++){
        			cout << a[i] << " ";
        		}
        		cout << a[count1 + count2] << endl;
        	}
        	else cout << "EMPTY" << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    MFC自绘框架窗口客户区
    命令行下创建mysql数据库
    linux重置mysql root密码的6种方
    xampp修改mysql默认密码详解
    Java常用包装类
    Java异常处理
    Java数组
    Java流程控制
    Java基本数据类型
    golang https server分析
  • 原文地址:https://www.cnblogs.com/zhuobo/p/10274078.html
Copyright © 2020-2023  润新知