打印由给定函数计算的每个级别的特定节点

时间:2015-09-02 07:40:57

标签: java algorithm data-structures tree traversal

在一次采访中,我获得了一项功能:

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-Array的每个级别n,我必须在每个级别打印f(n)节点。例如:

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)的{​​{1}}为n,则必须打印less than f(n)

我使用队列进行了基本级别的顺序遍历,但是当我知道任何级别node number nl%f(n) counting from the left的节点数是n时,如何计算每个级别的节点以及处理条件。 / p>

建议继续处理剩余部分问题的方法。

2 个答案:

答案 0 :(得分:1)

您需要执行级别订单遍历。

在下面的代码中,我假设有两种方法:

  • 一个是getFn(int level),它接受​​一个int并返回f(n)值;
  • 另一个是printNth(int i, Node n),它接收一个int和Node并精美地打印出#34; {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;
    }
}

答案 1 :(得分:0)

添加了解决方案here

我使用队列来读取特定级别的所有节点,在读取节点之前检查给定级别(n)是否等于当前级别然后检查队列的大小是否大于f(n)然后只读取f( n)队列中的节点并将其标记为已删除,否则执行mod操作并删除节点nl%f(n)。