有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    &&是二进制AND运算符。它只接受boolean个参数,所以不能将List传递给它

    由于要将输出添加到传递给方法的ArrayList,因此不需要返回类型,并且可以消除所有返回语句

    你可以这样写:

    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);
        }
    }
    

    如果希望通过递归方法创建输出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;
        }
    }