题目
给定一个 N 叉树,返回其节点值的后序遍历。
代码
小结:是先序遍历的变形,先序遍历是“根->左->右”,后序遍历是“左->右->根”,那么把先序遍历改成“根->右->左”,再逆序一下就是后序遍历。
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root == None:
return
s = [root]
cur = None
res = []
while s:
cur = s.pop()
res.insert(0, cur.val)
for child in cur.children:
s.append(child)
return res