简体   繁体   English

获取树中节点的祖先

[英]Get ancestors of a node in a tree

My tree looks something like this. 我的树看起来像这样。 I need to get all ancestors of a given node. 我需要获取给定节点的所有祖先。 A node can have multiple children and each child can in turn be a parent. 一个节点可以有多个子节点,而每个子节点又可以是父节点。

树

My code looks like this, this keeps returning undefined. 我的代码看起来像这样,这总是返回未定义的。 Please advise. 请指教。

  getAncestors(nodeId: number, ancestors: number[] = []): number[] {
    if (this.nodeId === nodeId) {
      return ancestors;
    }

    if (this.children.length > 0) {
      ancestors.push(this.nodeId);
    }

    for (const child of this.children) {
      child.getAncestors(nodeId,  ancestors);
    }

    return ancestors;
  }

Just reading this line should indicate a major red flag 刚刚阅读此行应指示一个重大的红色标志

child.getAncestors(nodeId,  ancestors);

If every time someone asks who all my ancestors are, I have to first ask my children who their parents are, at best my procedure is incredibly inefficient, and at worst this will encounter an infinite loop. 如果每次有人问我所有的祖先是谁,我必须首先问我的孩子,他们的父母是谁,充其量我的程序效率极低,最糟糕的是会遇到无限循环。 We should not call children in this function at all. 我们根本不应该在此函数中称呼孩子。

A correct solution would be dependent on the rest of this node class. 正确的解决方案将取决于此节点类的其余部分。 For example, if every node has access to the root, we could search from the root until we find the original node and track all the nodes we traveled along the way. 例如,如果每个节点都可以访问根,则可以从根进行搜索,直到找到原始节点并跟踪我们沿途经过的所有节点。 This could get messy. 这可能会变得混乱。

An easier solution would be to track all ancestors as each node is being created. 一个更简单的解决方案是在创建每个节点时跟踪所有祖先。 Consider the case of a file system, where the absolute path is required to access any file. 考虑文件系统的情况,其中访问任何文件都需要绝对路径。 You do need to update this list of ancestors if you predict you will rebalance and move nodes around often. 如果您预测自己将重新平衡并经常移动节点,则确实需要更新此祖先列表。

If nodes had access to their parents this can be done with a simple while loop and a pointer 如果节点可以访问其父节点,则可以通过一个简单的while循环和一个指针来完成

ancestors = [];
nodePtr = this;
while (nodePtr !== root) {
    nodePtr = nodePtr.parent();
    ancestors.push(nodePtr);
}
nodePtr.push(root);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM