Simple Java Solution. Same as level order traversal with a flag. No recursion


  • 2
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if(root==null) return result;
            
            Queue<TreeNode> q = new LinkedList<>();
            q.add(root);
            Boolean reverse = false;
            while(!q.isEmpty()){
                int size = q.size();
                List<Integer> temp = new ArrayList<>();
                for(int i=0;i<size;i++){
                    TreeNode node = q.poll();
                    if(!reverse)
                        temp.add(node.val);
                    else
                        temp.add(0,node.val);
                    if(node.left!=null) q.add(node.left);
                    if(node.right!= null) q.add(node.right);
                }
                result.add(temp);
                reverse=!reverse;
            }
            return result;
        }
    

Log in to reply
 

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