我正在阅读的一篇论文声称
很容易看出有一个线性时间算法来计算函数
l()
wherel()
给出最左边的孩子(输入和输出都在树的后序遍历中)。但是,我只能想到一个幼稚的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>();
...