【发布时间】:2019-10-13 17:24:26
【问题描述】:
给定以下树:
我应该返回从左到右遍历树的级别顺序: 所以上面的例子会输出一个列表列表:
[[3],[9,20],[15,7]]
我写了以下代码,想法是将节点值及其深度递归地存储在队列中,然后迭代队列元组并将中间列表 O 放入中间列表中,如果没有更多相同深度的节点将 O 附加到输出并清空 O 等等在。但是我的代码 Timeout 有什么帮助吗?
import queue
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
def helper(root,res,level):
if not root:
return res
l=level+1
res.put((root.val,level))
helper(root.left,res,l)
helper(root.right,res,l)
res=queue.Queue()
helper(root,res,0)
d=1
output=[]
node,depth=res.get()
output.append([node])
while res:
o=[]
node,depth=res.get()
while d ==depth:
o.append(node)
node,depth=res.get()
else:
d+=1
output.append(o)
return output
【问题讨论】:
-
请修正您的代码格式。
-
如果 9 有 1 或 2 个孩子,你能给出预期的输出吗?只是想确定它是否是正确的前序树遍历,或者它是否是您正在寻找的 BFS 遍历。
-
@san 如果 9 有一个孩子说“6”,输出应该是 [ [3], [9,20], [6,15,7] ]
-
@ElenaGT,好吧,它是一个 BFS。我刚刚发布了下面的解决方案作为答案。如果有帮助,请随时接受并投票。 :-)
标签: python data-structures tree breadth-first-search