Iterative Java Solution using Queue


  • 0
    C
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if(root==null)
                return result;
            Queue<TreeNode> q  = new LinkedList<>();
            boolean isTraverseLeft = true;
            q.add(root);
            while(!q.isEmpty()){
                int size = q.size();
                List<Integer> list = new ArrayList<>();
                for(int i=0; i<size; i++){
                    TreeNode t = q.poll();
                    if(isTraverseLeft) list.add(t.val);
                    else list.add(0,t.val);
                    
                    if(t.left!=null) q.add(t.left);
                    if(t.right!=null) q.add(t.right);
                }
                isTraverseLeft = !isTraverseLeft;
                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.