Simple Java Solution


  • 0
    Z
     
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if(root == null){
                return result;
            }
            
            Deque<TreeNode> deque = new LinkedList<>();
            deque.add(root);
            boolean positive = true;
            while (!deque.isEmpty()){
                int size = deque.size();
                List<Integer> list = new ArrayList<>();
                while (size-- > 0){
                    TreeNode node = positive ? deque.pollFirst() : deque.pollLast();
                    list.add(node.val);
                    if(positive){
                        if(node.left != null){
                            deque.add(node.left);
                        }
                        if(node.right != null){
                            deque.add(node.right);
                        }
                    }else {
                        if(node.right != null){
                            deque.addFirst(node.right);
                        }
                        if(node.left != null){
                            deque.addFirst(node.left);
                        }
                    }
    
                }
                positive = !positive;
                result.add(list);
            }
            return result;
        }
    }
    

Log in to reply
 

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