590. N叉树的后序遍历
给定一个 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]