剑指offer | 按之字形顺序打印二叉树

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

按之字形顺序打印二叉树

请实现一个函数按照之字顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,以此类推

分析:
使用两个栈实现

public class PrintTreeInZigzag<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;
        }

        Stack<Node>[] levels = new Stack[2];
        int current = 0;
        int next = 1;

        levels[current].push(node);
        while (!levels[0].empty() || !levels[1].empty()) {
            Node top = levels[current].pop();
            System.out.printf("%d\t", top.key);

            if (current == 0) {
                if (top.left != null) levels[next].push(top.left);
                if (top.right != null) levels[next].push(top.right);
            } else {
                if (top.right != null) levels[next].push(top.right);
                if (top.left != null) levels[next].push(top.left);
            }

            if (levels[current].empty()) {
                System.out.println();
                current = 1 - current;
                next = 1 - next;
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读