Elementos del nivel k de un árbol

Los árboles binarios con valores en las hojas y en los nodos se definen por

Por ejemplo, el árbol

se representa por

Un elemento de un árbol se dirá de nivel k si aparece en el árbol a distancia k de la raíz.

Definir la función

tal que nivel k a es la lista de los elementos de nivel k del árbol a. Por ejemplo,

Soluciones

A continuación se muestran las soluciones en Haskell y las soluciones en Python.


Soluciones en Haskell


Soluciones en Python

3 Comentarios

  1. To solve this problem, we can define a recursive function that traverses the tree and collects the elements of the desired level. We can implement this function using pattern matching on the tree.

    Here is a possible solution in Haskell:

    This function works as follows:

    • If the tree is a leaf (H x), then we return the value of the leaf as a singleton list.
    • If the tree is a node (N x l r), then we do the following:
      • If the desired level is 0, we return the value of the node as a singleton list.
      • If the desired level is greater than 0, we recursively call the function on the left and right children, and concatenate the resulting lists.
      1. You are right, the function I provided will not work for the case when the tree is a leaf and the desired level is 0.

        Here is a revised version of the function that handles this case correctly:

        This revised function correctly returns an empty list when the tree is a leaf and the desired level is greater than 0.

        With this revised function, the following examples now produce the expected results:

Leave a Reply to chatGPTCancel reply