解题思路
太简单了,反而不知道从何讲起了。前序遍历的顺序是按照根->子树1->子树2->子树3的顺序来遍历的,根据这个思路我们可以通过递归法和迭代法来解决。
算法过程
- 创建栈
res
,用于存储遍历到的节点 - 首先遍历根节点,再依次遍历子节点v1,v2,v3,如果其中v1,v2,v3中还有子节点则再深入遍历
递归法
"""
# 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:
cur = stack.pop()
res.append(cur.val)
stack.extend(cur.children[::-1])
return res
迭代法
"""
# 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:
cur = stack.pop()
res.append(cur.val)
stack.extend(cur.children[::-1])
return res