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

题目描述

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

例如,给定一个 3叉树 :
leetcode No.589 N叉树的前序遍历  (python3实现)
返回其前序遍历: [1,3,5,6,2,4]。
说明: 递归法很简单,你可以使用迭代法完成此题吗?

代码实现

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""
class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        res = []
        def helper(root):
            if not root:
                return 
            res.append(root.val)
            for child in root.children:
                helper(child)
        helper(root)
        return res

相关文章:

  • 2021-06-17
  • 2021-12-16
  • 2021-10-15
  • 2022-02-10
  • 2021-12-14
  • 2021-09-22
  • 2021-07-08
  • 2022-02-03
猜你喜欢
  • 2021-04-24
  • 2021-12-23
  • 2021-05-06
  • 2021-07-30
  • 2022-01-11
  • 2021-11-24
相关资源
相似解决方案