590. N叉树的后序遍历
Difficulty: 简单
给定一个 N 叉树,返回其节点值的_后序遍历_。
例如,给定一个 3叉树
:
返回其后序遍历: [5,6,3,2,4,1]
.
说明: 递归法很简单,你可以使用迭代法完成此题吗?
Solution
Language: ****
"""
# 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 = []
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]