How can I improve the complexity?


  • 0

    My code is as following, I have tried "LinkedList" and list.add(0, c.val), but no too much difference.
    I only beat 57.6% of submissions. Is there any possible way to improve in recursive way?

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        
        List<List<Integer>> r = new ArrayList();
        recur(r,root,0);
        if(r.size()>1){
            for(int i=2; i< r.size();i=i+2){
                 Collections.reverse(r.get(i));
            } 
        }
        return r;
    }
    
    private void recur(List<List<Integer>> r,TreeNode c, int d){
        if(c == null)  return;
        if(r.size() <= d){
            List<Integer> l = new ArrayList();
            l.add(c.val);
            r.add(l);
        } else {
            r.get(d).add(c.val);
        }
        
        d++;
        recur(r, c.right, d);
        recur(r, c.left, d);
    }

Log in to reply
 

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