Wrong Answer Error?


  • 4
    F
    public class Solution {
        public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
            //1.bfs and add them to a stack, 
            //but bfs from right to left, 
            //and add mark when finish a level
            //2.pop stack out and add to list
            
            if(root==null) return new ArrayList<ArrayList<Integer>>();
            //1:
            Queue<TreeNode> q=new LinkedList<TreeNode>();
            Stack<Integer>  s=new Stack<Integer>();
            q.add(root);
            TreeNode curr;
            s.push(-99);//push first marker
            int sc=0;//stack count:number of nodes in stack of this level level
            int nc=1;//node count: number of nodes in this level
            int nlnc=0;//next level node count:number of nodes in next level
            while(!q.isEmpty()){
                curr=q.poll();
                if(curr.right!=null) {q.add(curr.right); nlnc++;} 
                if(curr.left!=null)  {q.add(curr.left); nlnc++;}
                s.push(curr.val);
                sc++;
                if(sc==nc){//reach the end of the level
                    s.push(-99);//marker
                    sc=0;
                    nc=nlnc;
                    nlnc=0;
                }
            }
            s.pop();//pop the last marker
            //2.
            ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> currL=new ArrayList<Integer>();
            int c;
            while(!s.isEmpty()){
                c=s.pop();
                if(c!=-99){
                    currL.add(c);
                }else{
                    res.add(currL);
                    currL=new ArrayList<Integer>();
                }
            }
            return res;
            
        }
    }
    

    I got "Wrong Answer " But the answer seems the same with the expected answer.
    Is there something wrong with my code?
    Thanks


  • 0
    S

    nice solution


Log in to reply
 

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