In the case of Raiz
was NULL
, you are returning garbage, since in this case, folhaF
is not being initialized. In this case it is best to return zero.
I also see that you’re wearing ||
, but to check if the knot is leaf, it should be &&
.
As zentrunix noticed, you are also using struct NO **
when it should just be struct NO *
.
Also, I suggest renaming Raiz
for raiz
and somaFolha
for soma_folha
in order to conform to the standard of C.
And it makes the code very simple. I suggest that it stays that way:
int soma_folha(struct NO *raiz) {
if (raiz == NULL) return 0;
if (raiz->esq == NULL && raiz->dir == NULL) return raiz->valor;
return soma_folha(raiz->esq) + soma_folha(raiz->dir);
}
If you are a fan of the ternary operator, you can simplify a little more:
int soma_folha(struct NO *raiz) {
return raiz == NULL ? 0
: raiz->esq == NULL && raiz->dir == NULL ? raiz->valor
: soma_folha(raiz->esq) + soma_folha(raiz->dir);
}
In the title it is written "add all the nodes of a binary tree", but the function is called
somaFolha
. What you really want?– Jefferson Quesado