Unable to convert List> to return type IList>

前端 未结 3 1286
名媛妹妹
名媛妹妹 2021-01-18 01:31

For level order traversal why does this exception occur? Following exception occurs:

Cannot implicitly convert type \'System.Collections.Generic

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 02:13

    Just change the declaration of your result to List>.

    List implements IList, but List> does not implement IList>. Generic parameters are not covariant or contravariant unless defined that way and IList is not, so the type must match exactly.

    public IList> LevelOrder(TreeNode root)
    {
        var result = new List>();
        var que = new Queue();
    
        //if(root==null) return result;
    
        que.Enqueue(root);
        while (que.Count != 0)
        {
            int n = que.Count;
            var subList = new List();
            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;
    }
    

提交回复
热议问题