C/Visual C - ayuda con arboles

 
Vista:

ayuda con arboles

Publicado por cheke (3 intervenciones) el 15/05/2003 01:35:31
necesito ayuda con arboles balanceados y algun codigo para realizar el balanceo o algun ejemplo
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Alejandro

Implementación de árboles binarios balanceados

Publicado por Alejandro (1153 intervenciones) el 03/06/2025 00:17:10

Solución para árboles binarios balanceados



Los árboles binarios balanceados son estructuras de datos que mantienen su altura de manera que las operaciones de búsqueda, inserción y eliminación se realicen de manera eficiente. A continuación, te presento un ejemplo de cómo implementar un árbol AVL, que es un tipo de árbol binario balanceado.

Ejemplo de código en C para un árbol AVL



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <stdio.h>
#include <stdlib.h>
 
// Estructura de un nodo del árbol
struct Node {
    int key;
    struct Node* left;
    struct Node* right;
    int height;
};
 
// Función para obtener la altura de un nodo
int height(struct Node* N) {
    if (N == NULL)
        return 0;
    return N->height;
}
 
// Función para obtener el máximo de dos enteros
int max(int a, int b) {
    return (a > b) ? a : b;
}
 
// Función para crear un nuevo nodo
struct Node* newNode(int key) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->key = key;
    node->left = NULL;
    node->right = NULL;
    node->height = 1; // nuevo nodo es inicialmente agregado en hoja
    return node;
}
 
// Rotación a la derecha
struct Node* rightRotate(struct Node* y) {
    struct Node* x = y->left;
    struct Node* T2 = x->right;
 
    // Realizar rotación
    x->right = y;
    y->left = T2;
 
    // Actualizar alturas
    y->height = max(height(y->left), height(y->right)) + 1;
    x->height = max(height(x->left), height(x->right)) + 1;
 
    // Devolver nueva raíz
    return x;
}
 
// Rotación a la izquierda
struct Node* leftRotate(struct Node* x) {
    struct Node* y = x->right;
    struct Node* T2 = y->left;
 
    // Realizar rotación
    y->left = x;
    x->right = T2;
 
    // Actualizar alturas
    x->height = max(height(x->left), height(x->right)) + 1;
    y->height = max(height(y->left), height(y->right)) + 1;
 
    // Devolver nueva raíz
    return y;
}
 
// Obtener el factor de balanceo de un nodo
int getBalance(struct Node* N) {
    if (N == NULL)
        return 0;
    return height(N->left) - height(N->right);
}
 
// Función para insertar un nuevo nodo
struct Node* insert(struct Node* node, int key) {
    // 1. Realizar la inserción normal
    if (node == NULL)
        return newNode(key);
 
    if (key < node->key)
        node->left = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
    else // Duplicados no son permitidos
        return node;
 
    // 2. Actualizar la altura del nodo ancestro
    node->height = 1 + max(height(node->left), height(node->right)));
 
    // 3. Obtener el factor de balanceo
    int balance = getBalance(node);
 
    // Si el nodo se vuelve desbalanceado, hay 4 casos
 
    // Caso Izquierda Izquierda
    if (balance > 1 && key < node->left->key)
        return rightRotate(node);
 
    // Caso Derecha Derecha
    if (balance < -1 && key > node->right->key)
        return leftRotate(node);
 
    // Caso Izquierda Derecha
    if (balance > 1 && key > node->left->key) {
        node->left = leftRotate(node->left);
        return rightRotate(node);
    }
 
    // Caso Derecha Izquierda
    if (balance < -1 && key < node->right->key) {
        node->right = rightRotate(node->right);
        return leftRotate(node);
    }
 
    // Retornar el puntero del nodo (sin cambios)
    return node;
}
 
// Función para imprimir el árbol en orden
void inOrder(struct Node* root) {
    if (root != NULL) {
        inOrder(root->left);
        printf("%d ", root->key);
        inOrder(root->right);
    }
}
 
// Función principal
int main() {
    struct Node* root = NULL;
 
    // Insertar nodos
    root = insert(root, 10);
    root = insert(root, 20);
    root = insert(root, 30);
    root = insert(root, 40);
    root = insert(root, 50);
    root = insert(root, 25);
 
    // Imprimir el árbol en orden
    printf("Recorrido en orden del árbol AVL: ");
    inOrder(root);
 
    return 0;
}

Explicación del código


1. Estructura del nodo: Cada nodo tiene una clave, punteros a los nodos izquierdo y derecho, y una altura.
2. Funciones de rotación: Se implementan rotaciones a la izquierda y a la derecha para mantener el balance del árbol.
3. Inserción: La función `insert` inserta un nuevo nodo y ajusta el árbol para mantenerlo balanceado.
4. Recorrido en orden: La función `inOrder` imprime los nodos del árbol en orden ascendente.

Este código es un buen punto de partida para entender cómo funcionan los árboles binarios balanceados y cómo se pueden implementar en C.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar