oj-二叉树-java

Description

Given a Complete Binary tree, print the level order traversal in sorted order.

Input

The first line of the input contains integer T denoting the number of test cases. For each test case, the first line takes an integer n denoting the size of array i.e number of nodes followed by n-space separated integers denoting the nodes of the tree in level order fashion.(1<=T<=100;1<=n<=10^5)

Output

For each test case, the output is the level order sorted tree. ( Note: For every level, we only print distinct elements.)

Sample Input 1

2
7
7 6 5 4 3 2 1
6
5 6 4 9 2 1

Sample Output 1

7
5 6
1 2 3 4
5
4 6
1 2 9

Code

参考代码:
AdvancedAlgorithm

package org.alphacat.first;

import java.util.Arrays;
import java.util.Scanner;

public class TreeLevelOrder {

    //实现完全二叉树的层级遍历
    public static void levelOrder(int[] nums) {
        //对于完全二叉树,只有每层节点填满后才会填下一层节点
        //即除去最后一层外,每层节点个数均为2^h,其中根节点h=0,余下的节点全部填进最后一层
        int n = nums.length;
        int nodeCnt = 1;
        int index = 0;
        while (n - nodeCnt >= 0) {
            n -= nodeCnt;
            int[] nodes = new int[nodeCnt];
            for (int i = 0; i < nodeCnt; i++) {
                nodes[i] = nums[index++];
            }
            print(nodes);
            nodeCnt <<= 1;
        }
        if (n > 0) {
            int[] nodes = new int[n];
            for (int i = 0; i < n; i++) {
                nodes[i] = nums[index++];
            }
            print(nodes);
        }
    }

    //对每层节点进行排序去重输出
    public static void print(int[] nodes) {
        Arrays.sort(nodes);
        int i = 0;
        StringBuilder output = new StringBuilder();
        while (i < nodes.length) {
            int crrNode = nodes[i];
            output.append(crrNode + " ");

            //去重
            while (i < nodes.length && nodes[i] == crrNode) {
                i++;
            }
        }
        output.deleteCharAt(output.length() - 1);
        System.out.println(output.toString());
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int t = scanner.nextInt();
            for (int i = 0; i < t; i++) {
                int n = scanner.nextInt();
                int[] nums = new int[n];
                for (int j = 0; j < n; j++) {
                    nums[j] = scanner.nextInt();
                }
                levelOrder(nums);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值