Java层序遍历打印二叉树(有Null值)

public class Solution {

    public static void main(String[] args) {
        Integer[] arr = { 3, 9, 20, null, null, 15};
        // 根据数组构造出二叉树
        TreeNode treeNode = creatTreeNode(arr, 0);
        // 层序有Null值的打印二叉树
        printBinaryTree(treeNode);

    }

    // 根据数组构造二叉树
    public static TreeNode creatTreeNode(Integer[] arr, int index) {
        if (index >= arr.length) {
            return null;
        }

        if (arr[index] == null) {
            return null;
        }
        TreeNode root = new TreeNode(arr[index]);

        root.left = creatTreeNode(arr, index * 2 + 1);
        root.right = creatTreeNode(arr, index * 2 + 2);

        return root;
    }

    // 层序打印二叉树,存在null值
    public static void printBinaryTree(TreeNode root) {
        if (root == null)
            return;

        // 首先获取到二叉树的深度,用来判断终止条件
        int maxDepth = maxDepth(root);
        // 当前遍历到的二叉树高度
        int depth = 0;

        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> list = new ArrayList<>();

        queue.offer(root);
        while (!queue.isEmpty() && depth < maxDepth) {
            depth++;
            // 第一层为1 第二层为2 第三层为4 这是等比数列
            for (int i = 0; i < Math.pow(2, depth - 1); i++) {
                root = queue.poll();
                if (root == null) {
                    list.add(null);
                    queue.offer(null);
                    queue.offer(null);
                } else {
                    list.add(root.val);
                    queue.offer(root.left);
                    queue.offer(root.right);
                }
            }
        }

        list.forEach((item) -> {
            if (item == null) {
                System.out.print("null ");
            } else {
                System.out.print(item + " ");
            }
        });
    }

    // 获取到二叉树的深度
    public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        return (left > right ? left : right) + 1;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值