Подтвердить что ты не робот

Печать Определенные узлы на каждом уровне, вычисленные с помощью данной функции

В интервью мне была дана функция:

f(n)= square(f(n-1)) - square(f(n-2)); for n>2
f(1) = 1;
f(2) = 2;
Here n is the level of an n-array tree. f(n)=1,2,3,5,16...

Для каждого уровня n данного N-Array Мне нужно напечатать f (n) node на каждом уровне, Например:

At level 1 print node number 1 (i.e. root) 
At level 2 print node number 2 (from left)
At level 3 print node number 3 (from left)
At level 4 print node number 5... and so on

Если number of nodes(say nl) на любом уровне n равен less than f(n), тогда нужно распечатать node number nl%f(n) counting from the left.

Я выполнил обход порядка базового уровня с использованием очереди, но я застрял в том, как считать узлы на каждом уровне и обрабатывать условие, когда количество узлов на любом уровне n равно less than f(n).

Предложите путь для продолжения оставшейся части проблемы.

4b9b3361

Ответ 1

Вам нужно выполнить Обход порядка выполнения.

В приведенном ниже коде я принимаю два метода:

  • Один getFn(int level), который принимает int и возвращает значение f (n);
  • Другим является printNth(int i, Node n), который принимает int и Node и красиво печатает, что "{n} является желаемым для уровня {i}".

Код прост в реализации. Комментарии объясняют это как рассказ...

public void printNth throws IllegalArgumentException (Node root) {

    if (root == null) throw new IllegalArgumentException("Null root provided");

    //Beginning at level 1 - adding the root. Assumed that levels start from 1
    LinkedList<Node> parent = new LinkedList<>();
    parent.add(root)
    int level = 1;

    printNth(getFn(level), root);

    //Now beginning from the first set of parents, i.e. the root itself,
    //we dump all the children from left to right in another list.
    while (parent.size() > 0) { //Last level will have no children. Loop will break there.

        //Starting with a list to store the children
        LinkedList<Node> children = new LinkedList<>();

        //For each parent node add both children, left to right
        for (Node n: parent) {
            if (n.left != null) children.add(n.left);
            if (n.right != null) children.add(n.right);
        }

        //Now get the value of f(n) for this level
        level++;
        int f_n = getFn(level);

        //Now, if there are not sufficient elements in the list, print the list size
        //because children.size()%f(n) will be children.size() only!
        if (children.size() < f_n) System.out.println(children.size()); 
        else printNth(level, children.get(f_n - 1)); //f_n - 1 because index starts from 0

        //Finally, the children list of this level will serve as the new parent list 
        //for the level below.
        parent = children;
    }
}

Ответ 2

Добавлено решение здесь

Я использовал очередь для чтения всех узлов на определенном уровне, прежде чем читать узлы, проверяя, соответствует ли данный уровень (n) текущему уровню, а затем проверяет размер очереди больше, чем f (n), а затем просто читает f ( n) узлы из очереди и пометить их как удаленные, иначе выполните операцию mod и удалите node nl% f (n).