1. 程式人生 > 實用技巧 >LeetCode 589. N叉樹的前序遍歷

LeetCode 589. N叉樹的前序遍歷

589. N叉樹的前序遍歷

Difficulty: 簡單

給定一個 N 叉樹,返回其節點值的_前序遍歷_。

例如,給定一個3叉樹:

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

**說明:**遞迴法很簡單,你可以使用迭代法完成此題嗎?

Solution

Language: ****

"""
# 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]:
    if not root: return []
    stack, res = [root], []
    
    while stack:
      node = stack.pop()
      res.append(node.val)
      childs = node.children
      for i in range(len(node.children)-1, -1, -1):
        stack.append(childs[i])
              
    return res