python
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
ans=[]
def dfs_find (root):
# 终止条件
if root==None:
return
# 保存前序
# 遍历子节点
for child in root.children:
# 进入下一层
dfs_find(child)
ans.append(root.val)
dfs_find(root)
return ans
python
"""
# 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]:
# 保存结果数组
ans=[]
def dfs_find (root):
# 终止条件
if root==None:
return
# 保存前序
ans.append(root.val)
# 遍历子节点
for child in root.children:
# 进入下一层
dfs_find(child)
dfs_find(root)
return ans
python
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
# 广度优先搜索
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
# root 为空返回
if not root:
return[]
ans=list()
# 队列---root
q=deque([root])
# 广度搜索
while q:
cnt = len (q)
# 深度
level= list()
for _ in range (cnt):
cur=q.popleft()
level.append(cur.val)
for child in cur.children:
q.append(child)
ans.append(level)
return ans