题目
给定一个 N 叉树,返回其节点值的前序遍历。
说明: 递归法很简单,你可以使用迭代法完成
代码
"""
# 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]
"""
if root == None:
return
s = [root]
res = []
cur = root
while len(s) != 0:
cur = s.pop()
res.append(cur.val)
for i in range(len(cur.children) -1 , -1, -1):
s.append(cur.children[i])
return res