【发布时间】:2013-11-08 18:10:45
【问题描述】:
A paper我正在阅读声称
很容易看出有一个线性时间算法来计算函数
l()
其中l() 给出最左边的孩子(输入和输出都在树的后序遍历中)。但是,我只能想到一个幼稚的O(n^2) 实现,其中n 是树中的节点数。
例如,考虑以下树:
a
/ \
c b
在后序遍历中,树是c b a。对应的函数l() 应该给出c b c。
这是我在O(n^2) 时间的实现。
public Object[] computeFunctionL(){
ArrayList<String> l= new ArrayList<String>();
l= l(this, l);
return l.toArray();
}
private ArrayList<String> l(Node currentRoot, ArrayList<String> l){
for (int i= 0; i < currentRoot.children.size(); i++){
l= l(currentRoot.children.get(i), l);
}
while(currentRoot.children.size() != 0){
currentRoot= currentRoot.children.get(0);
}
l.add(currentRoot.label);
return l;
}
树是这样的:
public class Node {
private String label;
private ArrayList<Node> children= new ArrayList<Node>();
...
【问题讨论】:
-
有问题的树是如何存储的?
-
论文声称在第 8 页的第一段中存在线性时间算法。
-
我认为这是指找到给定节点的最左边的孩子?这不是从当前节点“向左走”,直到你到达一个没有左孩子的节点吗?那应该是线性的。
-
我不确定我是否理解。您能否提供一个明确的算法作为答案?
-
@Justin,是的,只有当您考虑一个节点时,它才是线性的。但是,如果您要计算所有
l(),那么它将是O(n^2)。或者您可能是说本文仅在考虑一个节点时才提及线性时间(但它将总体上是O(n^2))?
标签: algorithm data-structures tree theory graph-theory