-1

I am making a Quadtree in C++. I need to find the leaf nodes of the tree. To do this I have this function that needs to return a vector of the leaf nodes. For now everything else seems to work, but this function doesn't and I don't understand why.

vector<QuadTree*> find_leaves(QuadTree* quad, vector<QuadTree*>& list_of_leaves) {


    if (quad->is_leaf) {
        list_of_leaves.push_back(quad);
    }

    else {
        for (int i = 0; i < 4; i++) {
            find_leaves(quad->children[i], list_of_leaves);
        }
    }
    return list_of_leaves;
}

Before doing it in C++ I did it in Python (which I know much better). This function does the same thing but in Python and works just fine :

def find_leaves(quad, list_of_leaves = []):

    if quad.is_leaf:
        list_of_leaves.append(quad)

    else:
        for i in quad.children:
            find_leaves(i, list_of_leaves)

    return list_of_leaves

In both these codes quad is a node of the tree. Does anyone see where the error is, or does anyone know another way to find leaf nodes in a QuadTree? Thank you for your help.

1 Answers1

1

You are returning an empty vector, a temporary instead of the original.

Try this instead:

void find_leaves(QuadTree* quad, vector<QuadTree*>& list_of_leaves) {


    if (quad->is_leaf) {
        list_of_leaves.push_back(quad);
    }

    else {
        for (int i = 0; i < 4; i++) {
            find_leaves(quad->children[i], list_of_leaves);
        }
    }
}