Ottieni fattore di bilanciamento
Lezione 6 di 16 del corso Albero AVL - Serie sulle strutture dati #10 di Coddy.
Il fattore di bilanciamento di un nodo è getHeight(node.left) - getHeight(node.right). Un numero positivo significa che il lato sinistro è più alto, un numero negativo significa che il lato destro è più alto e 0 significa che sono alla stessa altezza.
Un nodo è considerato bilanciato finché il suo fattore di bilanciamento è -1, 0 o 1. Qualsiasi valore al di fuori di questo intervallo (2 o più, oppure -2 o meno) è ciò che innesca una rotazione.
Sfida
PrincipianteScrivi un metodo getBalance(node) in AVLTree che restituisce 0 se node è null, altrimenti restituisce getHeight(node.left) - getHeight(node.right).
Provalo tu
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "avltree.h"
static Node* mkNodeWithHeight(int h) {
Node* n = Node_create(0);
n->height = h;
return n;
}
int main(void) {
AVLTree* tree = AVLTree_create();
char line[256];
while (fgets(line, sizeof(line), stdin) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
char lTok[64];
char rTok[64];
sscanf(line, "%63s %63s", lTok, rTok);
Node* root = Node_create(0);
root->left = NULL;
if (strcmp(lTok, "null") != 0) {
root->left = mkNodeWithHeight(atoi(lTok));
}
root->right = NULL;
if (strcmp(rTok, "null") != 0) {
root->right = mkNodeWithHeight(atoi(rTok));
}
printf("%d\n", AVLTree_getBalance(tree, root));
}
return 0;
}
Tutte le lezioni di Albero AVL - Serie sulle strutture dati #10
2Progetto sugli alberi AVL
Classe NodoClasse AVLTreeEsercitati da solo: Compilatore C online