1

I have to do a function where, given an int n and a binary search tree, i have to convert the level n of the bst int a linked list. for example if given the numer 2 and this tree

      2
     /  \
    5    3

i have to make a liked list with 5 - 3

I have problems getting to the level given, and then getting each node on that level, because if i do reach the level i don't know how to reach the next node. Meaning, i can only get to the level on only one branch, and i cant think of any way to do it recursively.

so this is the struct for the bst and the linked chain:

struct nodo {
    info_t dato; 
    nodo *anterior;
    nodo *siguiente;
};
struct rep_cadena {
    nodo *inicio;
    nodo *final;
};
struct rep_binario {
    info_t dato;
    rep_binario *izq;
    rep_binario *der;
}; 

and this is the function i cant figure out:

cadena_t nivel_en_binario(nat l, binario_t b)

i have tried using another function i already made, that calculates the height of a tree, but i can't stop on the wanted level.

nat altura_binario(binario_t b) {
    if (b==NULL) return 0;
    else return maximo(altura_binario(b->izq), altura_binario(b->der))+ 1;
    }

where maximo() returns the highest number between the two given numbers.

iamuma
  • 11
  • 3

1 Answers1

0

You can do this by implementing Breadth-first_search algorithm, and modifying a little bit. Instead of enqueuing just nodes, you can enqueue pairs of (node, level) (where node level = parent level + 1), and then when enqueuing you can check if you have reached the desired level, and just output it as the result instead of queuing it further.

Pseudocode sketch:

target_level = ...read from input...

let level_nodes = ...an empty list...

let queue = ...an empty queue...
queue.enqueue((root_node, 0))

while queue is not empty:
    node, level = queue.dequeue()
    if level == target_level:
        level_nodes.append(node)
    else:
        if node has left child:
            queue.enqueue((left_child_node, level + 1))
        if node has right child:
            queue.enqueue((right_child_node, level + 1))
battlmonstr
  • 5,841
  • 1
  • 23
  • 33
  • that is a good solution, the thing is i cant use queues, i can only use the structures listed above or simple structures (like arrays, etc.). Maybe i can try and do this with only lists, and all the functions i already have (like remove first and last). – iamuma Apr 13 '19 at 16:45
  • Yes, you can use your list structure for the queue as it has both head and tail pointers. – battlmonstr Apr 14 '19 at 09:48