LeetCode 590. N叉樹的後序遍歷
阿新 • • 發佈:2020-12-08
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]