【发布时间】:2020-01-22 09:44:58
【问题描述】:
我尝试了几种不同的方法来解决这个问题。
我的代码的节点定义为:
节点是一个对象
- 值:数字
- children:节点列表
class Node:
def __init__(self, key, childnodes):
self.key = key
self.childnodes = childnodes
def __repr__(self):
return f'Node({self.key!r}, {self.childnodes!r})'
testTree = Node(1, [Node(2, []), Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])])
我已经接近用代码完成问题了:
def sum_of_nodes(root):
sum = 0
while root:
sum += root.key
print(sum)
root = root.childnodes
print(root)
root = root.pop()
print(root)
print(sum)
但是,它跳过了代码的某些部分,我不确定如何修复它。上面代码的结果是:
1
[Node(2, []), Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])]
Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])
4
[Node(4, [Node(5, []), Node(6, [Node(7, [])])])]
Node(4, [Node(5, []), Node(6, [Node(7, [])])])
8
[Node(5, []), Node(6, [Node(7, [])])]
Node(6, [Node(7, [])])
14
[Node(7, [])]
Node(7, [])
21
[]
还有一个错误:
Traceback (most recent call last):
File "D:/Documents/project1.py", line 191, in <module>
print(f'itersum_of_nodes(testTree) => {itersum_of_nodes(testTree)}') # 28
File "D:/Documents/project1.py", line 108, in sum_of_nodes
root = root.pop()
IndexError: pop from empty list
我也尝试过 geeksforgeeks.org/inorder-tree-traversal-without-recursion/ 教授的方法,但是,我的子节点被定义为列表而不是 .right 或 .left,我不确定如何从中获取我需要的信息。代码是:
stack = []
sum = 0
current = root
while True:
if current.childnodes[0] is not None:
stack.append(current)
current = current.childnodes[0]
elif stack:
current = stack.pop()
sum += current.value
current = current.childnodes[1]
else:
break
【问题讨论】:
标签: python-3.x tree