给定一个 N 叉树,返回其节点值的后序遍历

例如,给定一个 3叉树 :

Leetcode- 590. N叉树的后序遍历Leetcode- 590. N叉树的后序遍历Leetcode- 590. N叉树的后序遍历

Leetcode- 590. N叉树的后序遍历

返回其后序遍历: [5,6,3,2,4,1].

code:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if not root:                  #树为空就返回
            return []
        if not root.children:         #到达叶子结点返回值
            return [root.val]
        res=[]
        for c in root.children:
            res.extend(self.postorder(c))    #extend是将list每个元素取出后再加入列表中,而
                                             #append是将整个list作为一个元素加入到列表末尾
        res.append(root.val)          #最后的时候添加子孩子都遍历完之后的结点值
        return res                    #返回本次遍历后的list列表

思路草图:

Leetcode- 590. N叉树的后序遍历

Leetcode- 590. N叉树的后序遍历

相关文章:

  • 2021-07-13
  • 2021-06-17
  • 2021-09-11
  • 2021-04-22
  • 2021-04-24
  • 2021-11-07
  • 2021-07-08
猜你喜欢
  • 2021-04-19
  • 2021-11-26
  • 2021-11-26
  • 2021-05-06
  • 2021-12-26
  • 2021-10-19
相关资源
相似解决方案