簡體   English   中英

初始化二叉樹的兩個子樹而不出現“二元運算符的錯誤操作數類型”錯誤?

[英]Initialize both subtrees of a binary tree without getting "bad operand types for binary operator" error?

我無法理解為什么我不能在同一語句中初始化樹的兩邊。 我的任務是遞歸返回二叉樹所有葉子的列表(如果樹為空則返回 null),但我得到的只是

"error: bad operand types for binary operator '&&'
    return nbrLeaves(root.left, pong) && nbrLeaves(root.right, pong);"

我假設已經實現了帶有節點的二叉樹 class。

我的代碼如下:

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

&&是二元與運算符。 它只接受boolean arguments,所以你不能將List傳遞給它。

由於您將 output 添加到傳遞給您的方法的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);
    }
}

如果希望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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM