给定一个 N 叉树,返回其节点值的前序遍历。
Iterative:
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
res= []
stack = [root]
while stack:
cur = stack.pop()
res.append(cur.val)
stack.extend(reversed(cur.children))
return res
Recursive:
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
res= [root.val]
for child in root.children:
res.extend(self.preorder(child))
return res