LeetCode #589 #590 2018-08-07

589. N-ary Tree Preorder Traversal

https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/

这道题与二叉树的遍历很类似,同样可以使用递归和迭代两种方法来解。递归非常好实现,迭代需要注意使用栈结构和children入栈的顺序。
递归代码如下:

"""
# 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]
        """
        result = []
        self.helper(root, result)
        return result
    
    def helper(self, root, result):
        if not root:
            return
        result.append(root.val)
        for child in root.children:
            self.helper(child, result)

迭代代码如下:

"""
# 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]
        """
        result = []
        if not root:
            return result
        stack = [root]
        while stack:
            node = stack.pop()
            result.append(node.val)
            stack += [child for child in node.children[::-1] if child]
        return result

590. N-ary Tree Postorder Traversal

https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/

解法与上一题基本相同,不再赘述。
递归代码如下:

"""
# 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]
        """
        result = []
        self.helper(root, result)
        return result
    
    def helper(self, root, result):
        if not root:
            return
        for child in root.children:
            self.helper(child, result)
        result.append(root.val)

迭代代码如下:

"""
# 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]
        """
        result = []
        if not root:
            return result
        stack = [root]
        while stack:
            node = stack.pop()
            result.append(node.val)
            stack += node.children
        return result[::-1]

你可能感兴趣的:(LeetCode #589 #590 2018-08-07)