Strictly binary tree

Asked

Viewed 790 times

5

A binary search tree is strictly binary if all tree nodes have 2 children or none. Implement a function that checks whether a binary search tree is strictly binary.

// Estrutura de dados
typedef struct {
    int chave;
}tipo_elemento;

typedef struct nodo{
    struct nodo *dir, *esq;
    tipo_elemento e;
}tipo_nodo;

typedef tipo_nodo *apontador;

// Implementação
int estritamente_bin(apontador a){
    if(!a->dir && !a->esq)
        return 1;

    if(a->dir && a->esq)
        return estritamente_bin(a->esq) && estritamente_bin(a->dir);

    return 0;
}

Any suggestions and/or criticism to improve the above implementation?

  • Your code is correct. If tree change operations are few, but state query operations are many, it is possible to insert some metadata into tree nodes to contain this information and be more efficient. I’m not sure either code review is appropriate to the Sopt model, so vote for closure

1 answer

4


Your code is fine, I just have a few suggestions.

The first is about this:

typedef tipo_nodo *apontador;

That, I think, does not contribute much to the readability of the code. I think it is important that pointers are clearly treated as such, especially when using the operator ->, and therefore I suggest using tipo_nodo * in function estritamente_bin.

The function estritamente_bin can be reduced to that:

int estritamente_bin(tipo_nodo *a) {
    return (!a->dir && !a->esq)
            || (a->dir && a->esq && estritamente_bin(a->esq) && estritamente_bin(a->dir));
}
  • Thanks for the suggestions!

Browser other questions tagged

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