2021届秋招--猿辅导笔试--构建完全二叉树并遍历最外圈

题目描述:输入一个n,层次遍历构建完全二叉树,逆时针输出最外围的一圈

public class Num1 {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] numArr = new int[N+1];//1-N存放
        int inputN = 0;
        LinkedList resNum = new LinkedList<>();
        while (inputN < N){
            numArr[inputN+1] = in.nextInt();
            inputN++;
        }
        int tempN = 2;//满二叉树的个数+1
        int levelN = 1;//层数
        while (true){
            if (tempN > N){
                break;
            }
            levelN++;
            tempN = tempN * 2;
        }
        int tempLevel = 1;
        int tempIndex = 1;
        //把左边加进去(包括左下角)
        while (tempLevel <= levelN){
            resNum.add(numArr[tempIndex]);
            tempIndex = tempIndex * 2;
            tempLevel++;
        }
        //加进去下边
        tempIndex = tempIndex/2;//最后一层起始
        resNum.removeLast();
        int lastNum = 0;
        int lastMaxNum = tempN/2;
        for (int i = tempIndex; i <= N; ++i){
            lastNum++;
            resNum.add(numArr[i]);
        }
        if (lastNum == lastMaxNum){
            //最后一层就是满的
            int lastIndex = lastMaxNum-1;
            while (lastIndex > 2){
                resNum.add(numArr[lastIndex-1]);
                lastIndex = lastIndex/2;
            }
        }else {
            //不是满的
             if (lastNum%2 == 1){
                 lastNum++;
             }
             lastNum = lastNum/2;
             for (int i = lastMaxNum/2 + lastNum; i < lastMaxNum; ++i){
                 resNum.add(numArr[i]);
             }
             lastMaxNum = lastMaxNum/2;
             int lastIndex = lastMaxNum -1;
             while (lastIndex > 2){
                resNum.add(numArr[lastIndex]);
                lastIndex = lastIndex/2;
             }
        }
        StringBuilder resString = new StringBuilder();
        for (int i = 0; i < resNum.size()-1; ++i){
            resString.append(resNum.get(i));
            resString.append(" ");
        }
        resString.append(resNum.getLast());
        System.out.println(resString.toString());
    }

 

你可能感兴趣的:(Java,java,算法)