144.二叉树的前序遍历

递归解法

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) if root else []

迭代解法

TODO

94.二叉树的中序遍历

递归解法

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        return self.preorderTraversal(root.left) + [root.val] + self.preorderTraversal(root.right) if root else []

迭代解法

TODO

589.N 叉树的前序遍历

题目描述

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

例如,给定一个 3叉树 :

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

递归解法

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

class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if root == None:return []
        res = [root.val]
        for node in root.children:
            res.extend(self.preorder(node))
        return res

迭代解法

TODO

590.N 叉树的后序遍历

递归解法

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

迭代解法

TODO

Last modification:February 2nd, 2021 at 11:36 am