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;
    }
}

posted @ 2023-05-01 10:38  炸天帮帮主  阅读(30)  评论(0编辑  收藏  举报