Help! What's wrong with my code?


  • 0
    J
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (root == null) {
                return res;
            }
            Queue<TreeNode> cur = new LinkedList<TreeNode>();
            Queue<TreeNode> next = new LinkedList<TreeNode>();
            cur.offer(root);
            int level = 1;
            while (!cur.isEmpty() || !next.isEmpty()) {
                List<Integer> tmp = new ArrayList<Integer>();
            
                while (!cur.isEmpty()) {
                    TreeNode node = cur.poll();
                    tmp.add(node.val);
                    if (level % 2 != 0) {
                        if (node.right != null) {
                            next.offer(node.right);
                         }
                        if (node.left != null) {
                            next.offer(node.left);
                         }
                    }else {
                        if (node.left != null) {
                            next.offer(node.left);
                            }
                        if (node.right != null) {
                            next.offer(node.right);
                        }
                    }
                }
                level++;
                res.add(tmp);
                cur = next;
                next = new LinkedList<TreeNode>();
            }
            return res;
        }
    }

Log in to reply
 

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