标签:difficult append roo 说明 lang order root 图片 tree
Difficulty: 简单
给定一个 N 叉树,返回其节点值的_前序遍历_。
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
**说明: **递归法很简单,你可以使用迭代法完成此题吗?
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
标签:difficult append roo 说明 lang order root 图片 tree
原文地址:https://www.cnblogs.com/swordspoet/p/14102349.html