第十五天(树)
# 递归法
# 改成在函数里面嵌套函数才可以
# 不知道为什么直接用postorder作为递归函数会出问题,全局变量缓存?
def postorder(self, root: 'Node') -> List[int]:
result = []
def post(root):
if not root: #结点不存在直接返回
return
else: # 存在结点
if root.children: # 有孩子,优先遍历孩子
for i in root.children:
post(i)
result.append(root.val)
return result
post(root)
return result
# 迭代法,使用栈模拟树的遍历
def postorder(self, root: 'Node') -> List[int]:
if not root:
return None
stack_run = [root]
result = []
while stack_run:
node = stack_run.pop()
result.append(node.val)
children = node.children
for child in children:
if child:
stack_run.append(child)
result.reverse()
return result最后更新于