59.按之字形顺序打印二叉树

题目描述

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

解题思路

       利用Java中的LinkedList的底层实现是双向链表的特点;

      1)可用做队列,实现树的层次遍历;

      2)可双向遍历,奇数层时从前向后遍历,偶数层时从后向前遍历;

    private class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }
    }

    public ArrayList> Print(TreeNode pRoot) {
        ArrayList> ret = new ArrayList<>();

        if (pRoot == null) {
            return ret;
        }

        ArrayList list = new ArrayList<>();

        LinkedList queue = new LinkedList<>();

        queue.addLast(null);//层分隔符
        queue.addLast(pRoot);
        
        boolean leftToRight = true;

        while (queue.size() != 1) {
            TreeNode node = queue.removeFirst();
            
            if (node == null) {//到达层分隔符
                Iterator iter = null;
                
                if (leftToRight) {
                    iter = queue.iterator();//从前往后遍历
                } else {
                    iter = queue.descendingIterator();//从后往前遍历
                }
                
                leftToRight = !leftToRight;
                
                while (iter.hasNext()) {
                    TreeNode temp = (TreeNode)iter.next();
                    list.add(temp.val);
                }
                
                ret.add(new ArrayList(list));
                list.clear();
                
                queue.addLast(null);//添加层分隔符
                continue;              //一定要continue
            }
            
            if (node.left != null) {
                queue.addLast(node.left);
            }
            if (node.right != null) {
                queue.addLast(node.right);
            }
        }

        return ret;
    }

你可能感兴趣的:(剑指Offer,剑指Offer)