我编写了一个递归函数,用于计算 n 叉树中每个节点的后代数量。计算的结果在传入的数组中。我正在寻找一个以线性时间运行且不使用动态编程的函数。理想情况下,结果将设置在每个节点中,而不需要单独的数据结构。如果可能的话,递归是首选。
void setNumberDescendants(Node root, int[] descCount) {
for(Node child:root.children){
setNumberDescendants(child, descCount);
descCount[root.key] += 1+descCount[child.key];
}
}
class Node{
int key;
List<Node> children;
}