获取使用深度优先遍历二叉树的迭代器
我想使用 for 循环对二叉树进行深度优先遍历,并在每一步执行计算。
假设你有一个 4 层的树:
root
/ \
/ \
/ \
xx xx
/ \ / \
/ \ / \
xx xx xx xx
/ \ / \ / \ / \
x x x x x x x x
如果你把“深度优先探索树的步骤”放在一个列表中,它看起来像这样:
[
[1],
[1,1],
[1,1,1],
[1,1,0],
[1,0],
[1,0,1],
[1,0,0],
[0],
[0,1],
[0,1,0],
[0,1,1],
[0,0],
[0,0,1]
[0,0,0]
]
是否有一个函数,给定二叉树的层返回“步骤”列表中的“树探索”?
我的第一个想法是使用 itertools.permutation 库,但它没有给你正确的顺序。
我还尝试使用:
l = [False, True]
list(itertools.product(l, repeat=3))
Close 但它没有考虑到我在树的级别上上下下。
I want to do a depth first traversal of a binary tree using a for loop and perform calculations at each step.
Lets say you have a tree of 4 levels:
root
/ \
/ \
/ \
xx xx
/ \ / \
/ \ / \
xx xx xx xx
/ \ / \ / \ / \
x x x x x x x x
If you put the "steps of the depth first exploration of the tree" in a list it would look like this:
[
[1],
[1,1],
[1,1,1],
[1,1,0],
[1,0],
[1,0,1],
[1,0,0],
[0],
[0,1],
[0,1,0],
[0,1,1],
[0,0],
[0,0,1]
[0,0,0]
]
Is there a function that given the levels of a binary tree returns the "steps of the tree exploration" in a list?
My first though was to use the itertools.permutation
library but it doesn't give you the right order.
I also tried using:
l = [False, True]
list(itertools.product(l, repeat=3))
Close but it doesn't take into account that I'm going up and down the levels of the tree.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的二叉树是一个完美二叉树,您可以使用此函数:
然后对高度为 3 的树按如下方式调用它:
Assuming your binary tree is a perfect binary tree, you could use this function:
Then call it as follows for a tree with height 3: