是否可以使用Python以后序方式遍历一般树(即具有多个子节点的树)。本质上,我想从树中的左下角向上遍历一棵树,并将每个节点 .size
与其父节点 .size
进行比较,如果子节点是最大的,则更大,我将节点 .max_size
更改为子节点的 .size
。根将始终存储树中最大的值。
我的问题:有没有办法按后序遍历一般树(例如:E, F, B, C, D, A
)?如果是这样,这样做的方法是什么?
答案 0 :(得分:1)
不知道你为什么需要尺码的东西。你可以这样做:
In [254]: class Node:
...: def __init__(self, val: str):
...: self.val = val
...: self.children = []
...:
In [255]: A = Node('A')
In [256]: B = Node('B')
In [257]: C = Node('C')
In [258]: D = Node('D')
In [259]: E = Node('E')
In [260]: F = Node('F')
In [261]: A.children = [B,C,D]
In [262]: B.children = [E,F]
In [263]: root = A
# General post order but iterating over the children instead of doing left/right
In [264]: def post_order(root: Node):
...: if root is not None:
...: for child in root.children:
...: post_order(child)
...: print(root.val)
...:
In [265]: post_order(A)
E
F
B
C
D
A
答案 1 :(得分:1)
您可以递归地:
def updateNodeSize(node):
if 'children' not in node:
if 'size' in node:
return node['size']
return 0
maxSize = 0
for child in node['children']:
maxSize = max(maxSize, updateNodeSize(child))
node['size'] = maxSize
return maxSize
updateNodeSize(root)