Skip to content

Instantly share code, notes, and snippets.

@dev-math
Last active December 14, 2022 01:18
Show Gist options
  • Select an option

  • Save dev-math/a0d152c54ee4506f12e152c9e80a660d to your computer and use it in GitHub Desktop.

Select an option

Save dev-math/a0d152c54ee4506f12e152c9e80a660d to your computer and use it in GitHub Desktop.
// conta o numero de nos de uma arvore que tem chaves maiores que a chave que
// esta em um no P
int contarMaiores(NO *raiz, NO *p) {
if (!raiz) {
return 0;
}
if (raiz->chave > p->chave) {
return 1 + contarMaiores(raiz->esq, p) + contarMaiores(raiz->dir, p);
}
return contarMaiores(raiz->dir, p);
}
// outro jeito
int contarMaiores2(NO *raiz, NO *p, int *nos) {
if (raiz) {
if (raiz->chave > p->chave) {
(*nos)++;
}
contarMaiores2(raiz->esq, p, nos);
contarMaiores2(raiz->dir, p, nos);
}
return *nos;
}
// contar niveis de uma arvore
int contarNiveis(NO *raiz) {
if (!raiz) {
return 0;
}
int alturaEsquerda = contarNiveis(raiz->esq);
int alturaDireita = contarNiveis(raiz->dir);
if (alturaEsquerda > alturaDireita) {
return alturaEsquerda + 1;
} else {
return alturaDireita + 1;
}
}
// verifica se a arvore é binaria
bool verificaABB(NO *raiz) {
if (!raiz) {
return true;
}
if (raiz->esq && raiz->esq->chave > raiz->chave) {
return false;
}
if (raiz->dir && raiz->dir->chave < raiz->chave) {
return false;
}
return verificaABB(raiz->esq) && verificaABB(raiz->dir);
}
NO *listaFolhas(NO* raiz, NO **lista) {
if (raiz) {
if (!(raiz->esq) && !(raiz->dir)) {
NO *novo = (NO*) malloc(sizeof(NO));
novo->chave = raiz->chave;
novo->esq = *lista;
*lista = novo;
}
listaFolhas(raiz->esq, lista);
listaFolhas(raiz->dir, lista);
}
return *lista;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment