For level order traversal why does this exception occur? Following exception occurs:
Cannot implicitly convert type '
System.Collections.Generic.List<System.Collections.Generic.List<int>>
' to 'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>
'. An explicit conversion exists (are you missing a cast?)
public IList<IList<int>> LevelOrder(TreeNode root)
{
var result = new List<List<int>>();
var que = new Queue<TreeNode>();
//if(root==null) return result;
que.Enqueue(root);
while(que.Count!=0)
{
int n = que.Count;
var subList = new List<int>();
for(int i=0;i<n;i++)
{
if(que.Peek().left!=null)
que.Enqueue(que.Peek().left);
if(que.Peek().right!=null)
que.Enqueue(que.Peek().right);
subList.Add(que.Dequeue().val);
}
result.Add(subList);
}
return result;
}
All are obviously convertible to IList<T>. So you could create one of the specialized lists, cast it to an IList, and the cast it to one of the other implementations Imagine you have an object of List<List<int> and you would be allowed to cast it to IList<IList<int>>.
Use int () function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list. Simple example code converting [1, 2, 3] into one integer in 123. Use a list comprehension to construct a new list with str (int) applied to all elements.
You can only cast the outermost List to an IList. For example, this code would work: However, the generic type specified for the outermost list (T = List<int> in my example above) cannot be cast, even to an interface that it implements.
However, the generic type specified for the outermost list (T = List<int> in my example above) cannot be cast, even to an interface that it implements. Unless there is some reason you really need to return an IList, you can simply update your function definition to return a List instead of an IList.
Just change the declaration of your result to List<IList<int>>
.
List<T>
implements IList<T>
, but List<List<T>>
does not implement IList<IList<int>>
. Generic parameters are not covariant or contravariant unless defined that way and IList<T>
is not, so the type must match exactly.
public IList<IList<int>> LevelOrder(TreeNode root)
{
var result = new List<IList<int>>();
var que = new Queue<TreeNode>();
//if(root==null) return result;
que.Enqueue(root);
while (que.Count != 0)
{
int n = que.Count;
var subList = new List<int>();
for (int i = 0; i < n; i++)
{
if (que.Peek().left != null)
que.Enqueue(que.Peek().left);
if (que.Peek().right != null)
que.Enqueue(que.Peek().right);
subList.Add(que.Dequeue().val);
}
result.Add(subList);
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With