Los árboles se pueden representar mediante el siguiente tipo de datos
|
data Arbol a = N a [Arbol a] deriving Show |
Por ejemplo, los árboles
|
1 1 1 / \ / \ / \ 2 3 2 3 2 3 | /|\ /|\ | 4 4 5 6 4 5 6 7 |
se representan por
|
ej1, ej2, ej3 :: Arbol Int ej1 = N 1 [N 2 [],N 3 [N 4 []]] ej2 = N 1 [N 2 [], N 3 [N 4 [], N 5 [], N 6 []] ej3 = N 1 [N 2 [N 4 [], N 5 [], N 6 []], N 3 [N 7 []]] |
En el primer ejemplo la máxima ramificación es 2 (en el nodo 1 que tiene 2 hijos), la del segundo es 3 (en el nodo 3 que tiene 3 hijos) y la del tercero es 3 (en el nodo 3 que tiene 3 hijos).
Definir la función
|
maximaRamificacion :: Arbol a -> Int |
tal que (maximaRamificacion a) es la máxima ramificación del árbol a. Por ejemplo,
|
maximaRamificacion ej1 == 2 maximaRamificacion ej2 == 3 maximaRamificacion ej3 == 3 |
Soluciones
|
data Arbol a = N a [Arbol a] deriving Show ej1, ej2 :: Arbol Int ej1 = N 1 [N 2 [],N 3 [N 4 []]] ej2 = N 1 [N 2 [], N 3 [N 4 [], N 5 [], N 6 []]] ej3 = N 1 [N 2 [N 4 [], N 5 [], N 6 []], N 3 [N 7 []]] maximaRamificacion :: Arbol a -> Int maximaRamificacion (N _ []) = 0 maximaRamificacion (N x xs) = max (length xs) (maximum (map maximaRamificacion xs)) |
Se puede imprimir o compartir con