python实现深度遍历
时间: 2023-12-04 15:00:36 浏览: 60
深度遍历(Depth-First Search,DFS)是一种遍历图或树的算法,它从根节点开始遍历,沿着树的深度遍历子节点,当走到最深处时,再回溯到前一个节点,继续遍历其他子节点。以下是Python实现深度遍历的示例代码:
```python
# 定义节点类
class Node:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, node):
self.children.append(node)
# 深度遍历函数
def dfs(node):
print(node.value)
for child in node.children:
dfs(child)
# 测试代码
# 构建一棵树
root = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
node7 = Node(7)
node8 = Node(8)
node9 = Node(9)
root.add_child(node2)
root.add_child(node3)
node2.add_child(node4)
node2.add_child(node5)
node3.add_child(node6)
node3.add_child(node7)
node4.add_child(node8)
node5.add_child(node9)
# 深度遍历树
dfs(root)
```
输出结果:
```
1
2
4
8
5
9
3
6
7
```
阅读全文