590. N叉樹的後序遍歷
阿新 • • 發佈:2020-09-09
給定一個 N 叉樹,返回其節點值的後序遍歷。
例如,給定一個3叉樹
:
返回其後序遍歷:[5,6,3,2,4,1]
.
遞迴
""" # 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]: res=[] def helper(root): if not root: return None children=root.children for i in children: helper(i) res.append(root.val) helper(root) return res
迭代
""" # 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 [] res=[] stack=[root] while stack: node=stack.pop() res.append(node.val) for i in node.children: stack.append(i)return res[::-1]