剑指offer32 从上到下打印二叉树 Java

public class PrintBinaryTreeTopToBottom32 {
    static class Node {
        int val;
        Node left;
        Node right;
        public Node(int val){
            this.val = val;
        }
        @Override
        public String toString() {
            return "Node{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }

    public static void main(String[] args) {
        Node root = new Node(8);
        Node node21 = new Node(6);
        Node node22 = new Node(6);
        Node node31 = new Node(5);
        Node node32 = new Node(7);
        Node node33 = new Node(7);
        Node node34 = new Node(5);
        root.left = node21;
        root.right = node22;
        node21.left = node31;
        node21.right = node32;
        node22.left = node33;
        node22.right = node34;
        topToBottomWithLine(root);
    }

    private static void topToBottom(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if (root == null)
            return;
        queue.offer(root);
        while (!queue.isEmpty()) {
            Node temp = queue.poll();
            System.out.print(temp.val + " ");
            if (temp.left != null) {
                queue.offer(temp.left);
            }
            if (temp.right != null) {
                queue.offer(temp.right);
            }
        }
    }

    //分行从上到下打印二叉树
    private static void topToBottomWithLine(Node root) {
        if (root == null)
            return;
        int level = 0;
        int front = 0;
        int last = 1;
        int rear = 1;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        List list = new ArrayList();
        list.add(root.val);
        list.add(" ");
        while (!queue.isEmpty()) {
            Node q = queue.poll();
            front++;
            if (q.left != null) {
                queue.offer(q.left);
                rear++;
                list.add(q.left.val);
            }
            if (q.right != null) {
                queue.offer(q.right);
                rear++;
                list.add(q.right.val);
            }
            if (front == last) {
                level++;
                last = rear;
                list.add(" ");
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != " ") {
                System.out.print(list.get(i) + " ");
            } else
                System.out.println();
        }
    }
}

解释:借助队列,层次遍历

猜你喜欢

转载自blog.csdn.net/weixin_43065507/article/details/99334189