题目要求
Given an n-ary tree, return the postorder traversal of its nodes' values.
题目分析及思路
题目给出一棵N叉树,要求返回结点值的后序遍历。可以使用递归的方法做。因为是后序遍历,所以最后加入根结点的值。
python代码
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
order = []
if not root:
return order
for child in root.children:
order.extend(self.postorder(child))
order.append(root.val)
return order