在Python中,可以通过递归或者栈来实现树的深度优先搜索,通过队列来实现树的广度优先搜索。
首先,定义一个TreeNode类表示树节点:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
接下来,定义一个函数来实现深度优先搜索:
def dfs(node):
if node is None:
return
print(node.value)
dfs(node.left)
dfs(node.right)
定义一个函数来实现广度优先搜索:
from collections import deque
def bfs(node):
if node is None:
return
queue = deque()
queue.append(node)
while queue:
current = queue.popleft()
print(current.value)
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
接下来,创建一个二叉树并测试深度优先搜索和广度优先搜索:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
print("深度优先搜索:")
dfs(root)
print("\n广度优先搜索:")
bfs(root)
以上代码演示了如何实现树的深度优先搜索和广度优先搜索。深度优先搜索会先遍历完整的左子树,然后再遍历右子树,而广度优先搜索会先遍历同一层的所有节点,再遍历下一层的节点。