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

按之字形顺序打印二叉树

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

分析:
使用两个栈实现

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;
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容