擅长:python、mysql、java
<p>正如我在评论中所说的,你在找之前忘了附加你的后代
在你的藏品里。这是有效的:</p>
<pre><code>def find_descendants(parent, collections):
descendants = []
for descendant in collections[parent]:
descendants.append(descendant)
if descendant in collections:
descendants = descendants + find_descendants(descendant, collections)
return descendants
</code></pre>
<p>对于祖先,只需构建另一个<code>collections</code>,比如<code>ancestors_collection</code>,它存储了反向的后代/祖先关系。然后查找祖先的函数应该与find\u descents完全相同,您可以相应地对其进行重命名。在</p>
<p>编辑:</p>
<blockquote>
<p>Here a complete working code, I use <code>relative</code> to refer to ancestor or descendant:</p>
</blockquote>
^{pr2}$