顺序=[1,2,3,4,5,7,6,8,9,10,11,12,13,14,15]
这是顺序遍历
我想要像这样的水平顺序遍历
levelorder=[8,4,12,2,6,10,14,1,3,5,7,9,11,13,15]
我想过使用递归函数,比如
def rec(lis):
if(len(lis)<1):
return
mid = len(lis)//2
root = lis[math.ceil(mid)]
array.append(lis[root])
rec(lis[0:mid])
rec(lis[mid+1:])
但这不起作用,因为第二个递归调用只在所有第一个递归调用结束后发生。 有没有办法让我交替调用第一个和第二个递归调用
或者有没有其他方法可以在不构建树的情况下找到树的层次顺序遍历
当然,为什么不呢? 这不是最有效的实现,但适当的数据结构支持将使其达到渐近最优
相关问题 更多 >
编程相关推荐