103. Binary Tree Zigzag Level Order Traversal

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了103. Binary Tree Zigzag Level Order Traversal相关的知识,希望对你有一定的参考价值。

    /*
     * 103. Binary Tree Zigzag Level Order Traversal 
     * 11.21 By Mingyang
     */
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (root == null)
                return res;
            LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            int num = 0;
            boolean reverse = false;// a flag
            while (!queue.isEmpty()) {
                num = queue.size();
                List<Integer> levelres = new ArrayList<Integer>();
                for (int i = 0; i < num; i++) {
                    TreeNode node = queue.poll();
                    levelres.add(node.val);
                    if (node.left != null)
                        queue.add(node.left);
                    if (node.right != null)
                        queue.add(node.right);
                }
                if (reverse) {
                    Collections.reverse(levelres);
                    reverse = false;
                } else {
                    reverse = true;
                }
                res.add(levelres);
            }
            return res;
        }

 

以上是关于103. Binary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal

LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告

[leetcode tree]103. Binary Tree Zigzag Level Order Traversal

[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal