LeetCode 589 N-ary Tree Preorder Traversal (Python)

Posted by 小明MaxMing on April 21, 2021

题目

Given the root of an n-ary tree, return the preorder traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

解题思路

递归,先将根加入结果里,然后遍历所有子树

代码

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        def dfs(root):
            if root:
                res.append(root.val)
                for child in root.children:
                    dfs(child)    
        res = []
        dfs(root)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅