Reputation: 764
The following is my code for LeetCode binary tree level order traversal question. It gives a compile error on line 24, for no suitable method found for addAll(List), so I understand thats because addAll(Collections c) is not defined for abstract types i.e. list, but when I change the declaration of thisLevel to ArrayList, I still get the same error.
Why and how should the following be modified to make it a valid assignment?
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(root==null) return result;
LinkedList<TreeNode> parents=new LinkedList<TreeNode>();
List<TreeNode> children=new LinkedList<TreeNode>();
parents.add(root);
List<Integer> thisLevel=new ArrayList<Integer>();
while(parents.size()!=0 || children.size()!=0){
TreeNode p=parents.remove();
thisLevel.add(p.val);
if(p.left!=null) children.add(p.left);
if(p.right!=null) children.add(p.right);
if(parents.size()==0) {
result.addAll(thisLevel);
thisLevel=new ArrayList<Integer>();
parents=children;
children= new LinkedList<TreeNode>();
}
}
return result;
}
}
Upvotes: 1
Views: 4595
Reputation: 691973
The problem is that you're trying to add all the elements of a List<Integer>
to a List<List<Integer>>
. Since an Integer
is not a List<Integer>
, that doesn't compile.
Upvotes: 4