Java solution


  • 0
    B

    Similar as common level order traversal, the only difference is that the list storing values in the same level: one level is to add to the last, then the next is to add into the first, and in turn ....

    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new LinkedList<List<Integer>>();
            int level = 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            if (root != null) queue.offer(root);
            
            while (!queue.isEmpty()) {
                int size = queue.size();
                LinkedList<Integer> l = new LinkedList<Integer>();
                for (int i = 0; i < size; i++) {
                    TreeNode t = queue.poll();
                    if (t.left != null) queue.offer(t.left);
                    if (t.right != null) queue.offer(t.right);
                    if (level%2 == 1) {
                        l.addFirst(new Integer(t.val));
                    }else {
                        l.offer(new Integer(t.val));
                    }
                }
                level++;
                res.add(l);
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.