Algoritmo recursivo para contar el número de nodos hoja de un árbol binario
Idea de algoritmo:
Para cada nodo:
1. Si no tiene nodos secundarios, entonces es un nodo hoja.
2. Si tiene nodos secundarios, entonces el número de nodos de sus hojas = el número de nodos de hojas del cotiledón izquierdo y el número de nodos de hojas del cotiledón derecho.
Código del algoritmo: unsigned?int?getLeafCount(struct?node*?node)
{ if(node?==?NULL)?
return? 0; if(node-gt;left?==?NULL?amp;amp;?node-gt;right==NULL)?
return?1; ?getLeafCount(node-gt; left)
getLeafCount(node-gt; right);?
}
Complejidad del tiempo: O(n), Espacio complejidad: O(n)
------------------------------------- ----------- ----------
Adjunto se muestra un ejemplo: #include?lt;stdio.hgt; p>
#include?lt;stdlib .hgt;
/*?Un?árbol?binario?nodo?tiene?datos,?puntero?a?niño?izquierdo
y?un?puntero?al?niño correcto?*/
struct?node
{
int?data;
struct?node*?left;
struct?node*?right;
}
/*?Función?para?obtener?el?recuento ?de?leaf?nodos?en?a?binary?tree*/
unsigned?int?getLeafCount(struct?node*?node)
{ if(node?== ?NULL)?
return?0; if(node-gt;left?==?NULL?amp;amp;?node-gt;right==NULL)?
return?1; else
return?getLeafCount(node-gt;left)
getLeafCount(node-gt;right);?
}
/*?Función?auxiliar?que?asigna?un?nuevo?nodo?con?los
datos?dados?y?NULL?punteros?izquierdo?y?derecho.?*/
struct?node* ?newNode(int?data)
{ struct?node*?node?=?(struct?node*)
malloc( sizeof(struct?node)); nodo-gt;datos?=?datos; nodo-gt;izquierda?=?NULL;derecha?=?NULL; }
/*Controlador ?programa?para?probar?arriba?funciones*/?
int?main()
{ /*create?a? árbol*/?estructura?nodo?*raíz?=?nuevoNodo(1);
t-gt; izquierda=?nuevoNodo(2); raíz-gt; derecha=?nuevoNodo(3); izquierda-gt; izquierda?=?nuevoNodo(4); ?=?newNode(5); /*obtener?hojas?recuento?de?el?árbol?creado?arriba*/ printf("¿Hojas?recuento?de?el?árbol?es?d",?getLeafCount(raíz) ); getchar(); retorno?0;