作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在努力提高我的算法技能。所以,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
你应该将 10
和 14
分配给 root.right.left
和 root.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/
序 大家好呀,我是summo,这次来写写我在上班空闲(摸鱼)的时候做的一个小网站的事。去年阿里云不是推出了个活动嘛,2核2G的云服务器一年只要99块钱,懂行的人应该知道这个价格在业界已经是非常良心了
我尝试根据给定的级别顺序(BFS 顺序)构造 BST。我知道这是可能的,但我不知道我该怎么写。问题是我必须使用 BFS 序列。所以,我不能在这里使用递归,我必须迭代地编写我的程序......我发现这有
我是一名优秀的程序员,十分优秀!