[英]Initialize both subtrees of a binary tree without getting "bad operand types for binary operator" error?
I'm having trouble understanding why I can't initialize both sides of a tree in the same statement.我无法理解为什么我不能在同一语句中初始化树的两边。 The task I have is to recursively return a list of all the leaves of a binary tree (and return null if the tree is empty), but all I get is
我的任务是递归返回二叉树所有叶子的列表(如果树为空则返回 null),但我得到的只是
"error: bad operand types for binary operator '&&'
return nbrLeaves(root.left, pong) && nbrLeaves(root.right, pong);"
I am to assume that the binary tree class with nodes is already implemented.我假设已经实现了带有节点的二叉树 class。
My code is as follows:我的代码如下:
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);
}
&&
is the binary AND operator. &&
是二元与运算符。 It only accepts boolean
arguments, so you can't pass List
s to it.它只接受
boolean
arguments,所以你不能将List
传递给它。
Since you are adding the output to the ArrayList
passed to your method, it doesn't require a return type, and you can eliminate all the return statements.由于您将 output 添加到传递给您的方法的
ArrayList
,因此它不需要返回类型,您可以消除所有返回语句。
You can write it as follows:你可以这样写:
public void nbrLeaves(Node<E> root, List<E> pong) {
if (root.left == null && root.right == null) {
pong.add(root.element);
} else if (root.left != null && root.right == null) {
nbrLeaves(root.left, pong);
} else if (root.left == null && root.right != null) {
nbrLeaves(root.right, pong);
} else {
nbrLeaves(root.left, pong);
nbrLeaves(root.right, pong);
}
}
If you wish the output List
to be created by the recursive method instead of being passed to it, you can write it as follows:如果希望output
List
通过递归的方式创建,而不是传递给它,可以这样写:
public List<E> nbrLeaves(Node<E> root) {
if (root.left == null && root.right == null) {
List<E> pong = new ArrayList<>;
pong.add(root.element);
return pong;
} else if (root.left != null && root.right == null) {
return nbrLeaves(root.left);
} else if (root.left == null && root.right != null) {
return nbrLeaves(root.right);
} else {
List<E> left = nbrLeaves(root.left);
List<E> right = nbrLeaves(root.right);
left.addAll(right);
return left;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.