原题链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
解题思路:
- 递归略;
- 迭代法,仿照N叉树的前序遍历,前序遍历的顺序是【中、左、右】,只需实现【中、右、左】再反转得【左、右、中】即是后续遍历的结果;
Python3代码:
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
# 递归
def postorder(self, root: 'Node') -> List[int]:
if not root: return []
ans = []
if root.children:
for child in root.children:
ans.extend(self.postorder(child))
ans.extend([root.val])
return ans
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
# 迭代
def postorder(self, root: 'Node') -> List[int]:
if not root: return None
stack = [root]
ans = []
while stack:
node = stack.pop()
ans.append(node.val)
stack.extend(node.children)
return ans[::-1]