获取使用深度优先遍历二叉树的迭代器

发布于 2025-01-15 11:15:37 字数 655 浏览 3 评论 0原文

我想使用 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.permutationlibrary 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮萍、无处依 2025-01-22 11:15:37

假设您的二叉树是一个完美二叉树,您可以使用此函数:

def traverse(height, left=1, right=0):
    path = []
    while True:
        if len(path) < height:
            path.append(left)
        else:
            while path[-1] == right:
                path.pop()
                if not path:
                    return
            path[-1] = right
        yield path

然后对高度为 3 的树按如下方式调用它:

for path in traverse(3):
    print(path)

Assuming your binary tree is a perfect binary tree, you could use this function:

def traverse(height, left=1, right=0):
    path = []
    while True:
        if len(path) < height:
            path.append(left)
        else:
            while path[-1] == right:
                path.pop()
                if not path:
                    return
            path[-1] = right
        yield path

Then call it as follows for a tree with height 3:

for path in traverse(3):
    print(path)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文