java初始化二叉树的两个子树而不获取“二进制运算符的操作数类型错误”错误?
我很难理解为什么不能在同一个语句中初始化树的两侧。我的任务是递归地返回一个二叉树的所有叶子的列表(如果树是空的,则返回null),但我得到的是
"error: bad operand types for binary operator '&&'
return nbrLeaves(root.left, pong) && nbrLeaves(root.right, pong);"
我假设已经实现了带有节点的二叉树类
我的代码如下:
public List<E> leaves(){
List<E> pong = new ArrayList<E>();
if (root == null){
return pong;
}
nbrLeaves(root, pong);
return pong;
}
public List<E> nbrLeaves(Node<E> root, List<E> pong){
if (root.left == null && root.right == null){
pong.add(root.element);
}
if (root.left != null && root.right == null){
return nbrLeaves(root.left, pong);
}
if (root.left == null && root.right != null){
return nbrLeaves(root.right, pong);
}
return nbrLeaves(root.left, pong) && nbrLeaves(root.right, pong);
}
# 1 楼答案
&&
是二进制AND运算符。它只接受boolean
个参数,所以不能将List
传递给它由于要将输出添加到传递给方法的
ArrayList
,因此不需要返回类型,并且可以消除所有返回语句你可以这样写:
如果希望通过递归方法创建输出
List
,而不是传递给它,可以按如下方式编写: