zoukankan      html  css  js  c++  java
  • 树查找练习

    题目描述

    有一棵树,输出某一深度的所有节点,有则输出这些节点,无则输出EMPTY。该树是完全二叉树。 
    输入描述:
    输入有多组数据。
    每组输入一个n(1<=n<=1000),然后将树中的这n个节点依次输入,再输入一个d代表深度。
    输出描述:
    输出该树中第d层得所有节点,节点间用空格隔开,最后一个节点后没有空格。

    输入例子:
    4
    1 2 3 4
    2

    输出例子:
    2 3

    代码:
    import java.util.Scanner;
    
    public class 树查找 {
    
        public static void main(String[] args) {
            Scanner in =new Scanner(System.in);
            while(in.hasNext()){
                int count =in.nextInt();
                int[] num=new int[count];
                for(int i=0;i<count;i++){
                    num[i]=in.nextInt();
                }
                int flag=in.nextInt();
                int minAt=0,maxAt=0;
                for(int a=1;a<=flag;a++){
                    if(a<flag)
                        minAt+=Math.pow(2, a-1);
                    maxAt+=Math.pow(2, a-1);
                }
                if(minAt>count-1)
                    System.out.print("EMPTY");
                else if(maxAt>count-1)
                    maxAt=count;
                for(int j=minAt;j<maxAt;j++){
                    System.out.print(num[j]);
                    if(j<maxAt-1)
                        System.out.print(" ");
                }
            }
            in.close();
    
        }
    
    }

    利用了完全二叉树的层次的规律,2的几次方相加那种。



  • 相关阅读:
    田忌赛马 题解
    亚历山大的丢番图方程 题解
    zhx's contest题解
    芝麻OI比赛T7edges题解
    CSP-J2020游记
    Linux shell 学习笔记(五)
    Linux shell 学习笔记(四)
    Linux shell 学习笔记(三)
    Linux shell 学习笔记(二)
    Oracle并发
  • 原文地址:https://www.cnblogs.com/ygh1229/p/5693921.html
Copyright © 2011-2022 走看看