What are the errors of this chunk of C code that sums the nodes of a binary tree?

Asked

Viewed 207 times

0

int somaFolha(struct NO **Raiz)
{
  int somaF;

  if (Raiz != NULL)
  {
    if (Raiz->esq == NULL || Raiz->dir == NULL)
      somaF += Raiz->valor;
    else
    {
      somaF = somaFolha((*Raiz).esq);
      somaF += somaFolha(Raiz->dir);
    }
  }

  return somaF;
}
  • 1

    In the title it is written "add all the nodes of a binary tree", but the function is called somaFolha. What you really want?

1 answer

4

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);
}
  • Aah Thanks, What I didn’t understand was also this excerpt: somaF = somaFolha((*Root). Esq); somaF += somaFolla(Root->dir);

  • @Elvessousa The idea is to take the value of somaFolha of the left subtree, the value of the right subtree and add the two.

  • 1

    has a strange thing, I think the parameter "struct NO ** root" should only be "struct NO * root"...

  • @zentrunix It is true. Thank you very much for the remark.

  • 1

    I think it’s worth mentioning that folhaF has not been initialized and thus can return memory junk. Not that this will change your final code, but the AP asked to list all errors, it was not?

  • @Jeffersonquesado Feito.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.