我想通过遍历循环来创建二叉树。我知道如何编写一个非常基本的二叉树。
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None
root = Tree()
root.data = 75
root.left = Tree()
root.left.data = 95
root.right = Tree()
root.right.data = 64
root.left.left = Tree()
root.left.left.data = 32
root.left.right = Tree()
root.left.right.data = 93
root.left.left = Tree()
root.right.left.data = 32
root.left.right = Tree()
root.right.right.data = 93
print(root.data)
这很麻烦,如果我有一个数字列表:
list = [1,2,3,4,5,6,7]
并通过循环将其按此顺序创建二进制树,以便:
1
2 3
4 5 6 7
我该怎么写?并且因为我使用它来计算所有路径的总和,你如何导航/迭代二叉树:
答案 0 :(得分:4)
要从节点值列表构建完整的二叉树(不一定二进制搜索树),我们假设列表中的值按照级别排序 - 订单遍历。所以,你的问题列表
values = [1,2,3,4,5,6,7]
代表一棵树:
1
2 3
4 5 6 7
请注意,根值位于0
位置,其左侧子位于1*2-1=1
位置,右侧位于1*2=2
位置等。通常位于索引i
的列表,其左侧子项位于(i+1)*2-1
,右侧子项位于(i+1)*2
。
现在,我们只需要逐个节点地递归构建树,在每一步创建左侧和右侧子树。
为了简化,我们假设values
的列表是全局的。
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def buildTree(i):
if i < len(values):
return Node(values[i], left=buildTree((i+1)*2-1), right=buildTree((i+1)*2))
values = [1,2,3,4,5,6,7]
tree = buildTree(0)
要打印出树,我们可以使用preorder tree traversal:
def preorder(node):
if node is None:
return
yield node.data
for v in preorder(node.left):
yield v
for v in preorder(node.right):
yield v
像这样:
>>> print list(preorder(tree))
[1, 2, 4, 5, 3, 6, 7]
答案 1 :(得分:0)
这是一个快速,肮脏的迭代方法(因为你的问题确实提到了一个循环!),它使用一个列表和一个标志来跟踪刚插入的内容以及接下来需要做什么。内联评论:
def createTree(values):
_root = Tree()
_root.data = values[0]
nodes = [_root]
direction = 0 # 0 => left, 1 => right
for val in values[1:]:
root = nodes.pop(0) # pop the first element, this is the one whose children we need to create
node = Tree() # create the next child
node.data = val
if direction == 0: # we've to attach to the the left child
direction = 1 # reverse the direction
root.left = node # attach the child
nodes.insert(0, root) # put root back, we need to attach to its right child for the next value
nodes.append(node) # place the left child at the end of the queue/stack
else: # attach to right child
direction = 0 # reverse direction
root.right = node # do the attachment
nodes.append(node) # same policy as left node
return _root # done, now return
并测试我们的功能......
root = createTree([1, 2, 3, 4, 5, 6, 7])
print(root.data)
print(root.left.data)
print(root.right.data)
print(root.left.left.data)
print(root.left.right.data)
print(root.right.left.data)
print(root.right.right.data)
输出:
1
2
3
4
5
6
7