How this is working?? The first time ret add {{}} but where does it go at last??


  • 0
    K
      public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> ret = new ArrayList<List<Integer>>();
            if(root == null) return ret;
            
    		Stack<TreeNode> current = new Stack<TreeNode>();
            Stack<TreeNode> next = new Stack<TreeNode>();
            Stack<TreeNode> swap = null;
            List<Integer> level = new ArrayList<Integer>() ;
            current.push(root);
            int turn = 0;
           
            while(!current.isEmpty()){
                TreeNode temp = current.pop();
                if(temp != null){
                    if(current.isEmpty())
                        ret.add(level);
                    level.add(temp.val);
                
                    if(turn == 0){
                        if(temp.left != null) next.push(temp.left);
                        if(temp.right != null) next.push(temp.right);
                    }
                    if(turn == 1){
                        if(temp.right != null) next.push(temp.right);
                        if(temp.left != null) next.push(temp.left);
                    }
                   if(current.isEmpty()){
                        turn = 1-turn;
                        swap = current;
                        current = next;
                        next = swap;
                        level = new ArrayList<Integer>();
                   } 
               }
          }
          return ret;
        }

Log in to reply
 

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