Search code examples
javatreebinaryleaf

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

"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.

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

Solution

  • && is the binary AND operator. It only accepts boolean arguments, so you can't pass Lists to it.

    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.

    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:

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