剑指offer | 把二叉树打印成多行

2019-08-04  本文已影响0人  icebreakeros

把二叉树打印成多行

从上到下按层打印成多行

分析:
使用队列

public class PrintTreeInLines<Key extends Comparable<Key>> {

    private class Node {
        public Key key;
        public Node left, right;

        public Node(Key key) {
            this.key = key;
        }
    }

    public void print(Node node) {
        if (node == null) {
            return;
        }

        Queue<Node> queue = new LinkedList<>();
        queue.add(node);
        int nextLevel = 0; // 下一层结点数
        int printed = 1; // 当前层没有打印的结点数
        while (!queue.isEmpty()) {
            Node current = queue.peek();
            System.out.printf("%d\t", current.key);

            if (current.left != null) {
                queue.add(current.left);
                ++nextLevel;
            }

            if (current.right != null) {
                queue.add(current.right);
                ++nextLevel;
            }

            queue.remove();
            --printed;
            if (printed == 0) {
                System.out.println("");
                printed =  nextLevel;
                nextLevel = 0;
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读