Solution can't add integer to ArrayList. wrong answer


  • 0
    N

    the fact is rescell.add(val) doesn't work. Can anyone help me out?

    public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root){
        int top=0;
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> resCell=new ArrayList<Integer>();
        List<TreeNode> TreeQ=new ArrayList<>();
        List<TreeNode> TempQ=new ArrayList<>();
    
        if(root==null) return res;
        TreeQ.add(root);
        
        
        while(true){
            resCell.clear();
            TempQ.clear();
            while(!TreeQ.isEmpty()){
                TreeNode topNode=TreeQ.get(top);
                TreeQ.remove(top);
                if(topNode.left!=null) TempQ.add(topNode.left);
                if(topNode.right!=null) TempQ.add(topNode.right);
                resCell.add(topNode.val);
            }
            res.add(resCell);
            TreeQ=TempQ;
            if(TreeQ.isEmpty())
                break;
        }
        return res;
    }
    

    }

    Input:
    [1,2]
    Output:
    [[],[]]
    Expected:
    [[1],[2]]

  • 1
    A

    The problem is the wrong usage of the method clear in resCell.clear(). After adding resCell to res, your code goes back to the beginning of the while(true). Since the reference of resCell is the same as the one just added to res, you are cleaning the information that you have just added!

    To solve this, just create a new reference in each iteration:

    resCell = new ArrayList<Integer>();

    That should do.


  • 0
    N

    Thanks for your reply. You are absolutely right. I think I misunderstood shallow copy and deep copy and the class method addAll does the same thing.


Log in to reply
 

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