gpt4 book ai didi

python - Python中的前序遍历

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:36 29 4
gpt4 key购买 nike

我正在努力提高我的算法技能。所以,btree的前序遍历:这是我的尝试。

class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right

def preorder(node):
if not node: return None
print node.val
preorder(node.left)
preorder(node.right)


root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
tree ="""
20
8 22
4 12 10 14
"""
print tree
preorder(root)

20
8
4
12
10
14
22

但这是错误的..因为 22 应该在 12.. 之后,对吧?

最佳答案

问题出在您的 Node 作业中 -

root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)

这创建的树看起来像 -

       20
8 22
4 12
10 14

为此,你得到的前序遍历是正确的。


对于你想要的树——

     20
8 22
4 12 10 14

你应该将 1014 分配给 root.right.leftroot.right.right ,不是 root.left.right.left 等。示例 -

root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.right.left = Node(10)
root.right.right = Node(14)

关于python - Python中的前序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32557894/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com