Java 打印由给定函数计算的每个级别上的特定节点
在一次采访中,我得到了一个功能:Java 打印由给定函数计算的每个级别上的特定节点,java,algorithm,data-structures,tree,traversal,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,我必须在每个级别打印fn节点。例如: At level 1 print node number 1 (i.e. root) At level 2 print node number
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,我必须在每个级别打印fn节点。例如:
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
如果任何级别n的节点编号nl小于fn,则必须从左侧打印节点编号nl%fn计数
我使用队列进行了一次基本的级别顺序遍历,但我被困在如何计算每个级别的节点数以及如何处理任意级别n的节点数小于fn的情况
建议继续解决问题剩余部分的方法。添加了解决方案
我使用队列读取特定级别上的所有节点,在读取节点之前,检查给定的级别n是否等于当前级别,然后检查队列的大小是否大于fn,然后仅从队列中读取fn节点并将其标记为已删除,否则执行mod操作并删除节点nl%fn。您需要执行级别顺序遍历
在下面的代码中,我假设有两种方法:
一个是getFnint-level,它接受一个int并返回fn值;
另一个是printnthin i,节点n接受一个int和节点,漂亮地打印出{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;
}
}
什么是n-数组树?@poorvankBhatia可以随时查询。