[leetcode] 103. 二叉树的锯齿形层次遍历

103. 二叉树的锯齿形层次遍历

按题号刷的优势体现出来了2333333

这题实际上就是上个题102. 二叉树的层次遍历的演变,把上个题结果的偶数行list反转一下即可。。

上题通过人数10k+,这个题才3k,我想这题不经过上题思路的引导很容易思路被带弯把

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = levelOrder(root);

        boolean flag = false;
        for (List<Integer> list : lists) {
            if (flag)
                Collections.reverse(list);
            flag = !flag;
        }

        return lists;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) return list;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        TreeNode flag = root;
        List<Integer> nowNumList = new ArrayList<>();
        list.add(nowNumList);

        while (!queue.isEmpty()) {
            TreeNode nowNode = queue.poll();
            nowNumList.add(nowNode.val);

            TreeNode sonNode = nowNode.left;
            if (sonNode != null) queue.offer(sonNode);

            sonNode = nowNode.right;
            if (sonNode != null) queue.offer(sonNode);

            if (flag == nowNode && !queue.isEmpty()) {
                nowNumList = new ArrayList<>();
                list.add(nowNumList);
                flag = queue.peekLast();
            }
        }
        return list;
    }
}
posted @ 2018-11-06 19:14 ACBingo 阅读(...) 评论(...) 编辑 收藏