Obtener factor de equilibrio
Lección 6 de 16 del curso Árbol AVL - Serie de Estructuras de Datos #10 de Coddy.
El factor de equilibrio de un nodo es getHeight(node.left) - getHeight(node.right). Un número positivo significa que el lado izquierdo es más alto, un número negativo significa que el lado derecho es más alto, y 0 significa que están equilibrados.
Un nodo se considera equilibrado siempre que su factor de equilibrio sea -1, 0 o 1. Cualquier valor fuera de ese rango (2 o más, o -2 o menos) es lo que desencadena una rotación.
Desafío
PrincipianteEscribe un método getBalance(node) en AVLTree que devuelva 0 si node es null, de lo contrario devuelve getHeight(node.left) - getHeight(node.right).
Pruébalo tú mismo
#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;
}
Todas las lecciones de Árbol AVL - Serie de Estructuras de Datos #10
2Proyecto de Árbol AVL
Clase NodoClase AVLTree