from functools import lru_cache
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
# 二叉树
visited = set()
@lru_cache
def DFS(node: TreeNode):
if node in visited:
return
# 处理当前层
visited.add(node)
# 开始递归
DFS(node.left)
DFS(node.right)
# 多叉树
visited = set()
def dfs(node: TreeNode, visited:set):
visited.add(node)
for next_node in node.children():
DFS(next_node, visited)
树的DFS遍历
最新推荐文章于 2024-03-24 22:28:04 发布