algorithm - 在线性时间内找到树中每个节点的最左边的子节点?

标签 algorithm data-structures tree theory graph-theory

A paper我正在阅读以下声明

It is easy to see that there is a linear time algorithm to compute the function 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>();
...

最佳答案

您可以使用一个简单的递归算法,可以在每个节点的 O(1) 时间内计算出此信息。由于总共有 n 个节点,因此运行总时间为 O(n)。

基本思想是以下递归见解:

  • 对于任何没有左子节点的节点 n,l(n) = n。
  • 否则,如果 n 有左 child L,则 l(n) = l(L)。

这产生了这种递归算法,它用每个节点的 l 值来注释:

function computeL(node n) {
   if n is null, return.

   computeL(n.left)
   computeL(n.right)

   if n has no left child:
      set n.l = n
   else
      set n.l = n.left.l

希望这有帮助!

关于algorithm - 在线性时间内找到树中每个节点的最左边的子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865740/

相关文章:

algorithm - 如何处理这个算法问题?

algorithm - 具有更新的 MEX 查询

java - 为什么在我的 LinkedBinaryTree 实现中只添加了根

tree - 如何计算序言中树的叶子?

algorithm - 基于堆栈的树遍历的时间复杂度

algorithm - 尝试检查树是否为二叉搜索树

c - 使用栈将中缀表达式转换为前缀时,如果被扫描的和栈顶运算符的优先级相同,应该怎么办?

java - 无需任何特殊数据结构即可计算移动平均线

python - 嵌套递归是可能的还是我们应该避免递归?

c++ - 不使用外部库的稀疏 vector 实现建议