A simple Java Level order solution


  • 0
    L
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            if(root==null) {
                return Collections.emptyList();
            }
            List<List<Integer>> list = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            byte turn = 0;
            while(!queue.isEmpty()) {
                int size = queue.size();
                LinkedList<Integer> ll = new LinkedList<>();
                while(size>0) {
                    TreeNode node = queue.poll();
                    if(turn==1) {
                        ll.addFirst(node.val);
                    }
                    else {
                        ll.addLast(node.val);
                    }
                    if(node.left!=null) {
                        queue.add(node.left);
                    }
                    if(node.right!=null) {
                        queue.add(node.right);
                    }
                    
                    size--;
                }
                list.add(ll);
                turn ^=1;
            }
            return list;
        }
    

Log in to reply
 

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