LeetCode之N叉树的后序遍历(590)

题目描述:

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

例如,给定一个 3叉树 :

LeetCode之N叉树的后序遍历(590)_第1张图片
返回其后序遍历: [5,6,3,2,4,1].

题目链接

知识点回顾:

此题考察树的后序遍历:

后序遍历:左子树结点、右子树结点、根节点
思路:
1.若树为空,则空操作返回
2.按照从左到右的顺序后序遍历根节点的每一颗子树即孩子。

题解一: 递归法

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution(object):
    def postorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        result=[]
        def postHelper(root):
            if not root:
                return None
            children = root.children
            for child in children:
                postHelper(child)
            result.append(root.val)

        postHelper(root)
        return result


题解二: 迭代法

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution(object):
    def postorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
    
        result = []
        if root == None: return result

        stack = [root]
        while stack:
            curr = stack.pop()
            result.append(curr.val)
            stack.extend(curr.children)

        return result[::-1]

你可能感兴趣的:(刷题,#,leetcode,#,树)