LeetCode 590(589). N叉树的后序遍历(Python)

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

例如,给定一个 3叉树 :

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

N叉树的不同之处在于子节点不再是left,right表示的,而是需要root.children[i]来遍历得到每一个子节点

递归方法:(内存消耗太大)

"""
# 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]
        """
        res = list()
        
        def append_child(root):
            if root is None:
                return
            
            child_index = 0
            
            while child_index < len(root.children):
                # 继续向下遍历子节点
                append_child(root.children[child_index])
                child_index += 1
                
            res.append(root.val)
        
        append_child(root)
        return res

迭代方法:

同理如果要返回前序遍历 [1,3,5,6,2,4]

递归方法:

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        res = list()
        
        def append_child(root):
            if root is None:
                return
            
            res.append(root.val)
            
            child_index = 0           
            while child_index < len(root.children):
                # 继续向下遍历子节点
                append_child(root.children[child_index])
                child_index += 1
                
            
        
        append_child(root)
        return res

迭代方法:

发布了88 篇原创文章 · 获赞 98 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/HNU_Csee_wjw/article/details/102516415
今日推荐