擅长:python、mysql、java
<p>可以使用堆栈处理嵌套结构:</p>
<ul>
<li>从最外层的列表开始,<em>reversed</em>作为堆栈,每个列表都有一个空元组,以跟踪<em>组织路径</em>。在</li>
<li>在<code>while stack:</code>循环中,从堆栈中获取顶层元素。做你需要做的事情,比如记录名字。从添加了当前组织名称的组织路径中生成一行。在</li>
<li>将<code>Children</code>键中的所有元素与父组织的组织路径一起添加到堆栈中。在</li>
<li>循环直到堆栈完成。在</li>
</ul>
<p>需要反转,因为从堆栈中获取元素的顺序是相反的。您仍然希望将堆栈用于此作业(而不是队列),因为我们希望首先输出信息深度。在</p>
<p>这看起来像这样:</p>
<pre><code>def flatten_orgs(orgs):
stack = [(o, ()) for o in reversed(orgs)] # organisation plus path
while stack:
org, path = stack.pop() # top element
path += (org['Name'],) # update path, adding the current name
yield path # give this path to the caller
# add all children to the stack, with the current path
stack += ((o, path) for o in reversed(org['Children']))
</code></pre>
<p>然后可以循环上述函数以获取所有路径:</p>
^{pr2}$