二叉树的深度遍历和广度遍历代码
时间: 2023-11-19 21:05:36 浏览: 88
好的,以下是二叉树的深度遍历和广度遍历的代码:
深度遍历(前序、中序、后序遍历)代码:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 递归前序遍历
def preorder_traversal(root):
if not root:
return
print(root.val) # 先输出根节点的值
preorder_traversal(root.left) # 遍历左子树
preorder_traversal(root.right) # 遍历右子树
# 递归中序遍历
def inorder_traversal(root):
if not root:
return
inorder_traversal(root.left) # 遍历左子树
print(root.val) # 先输出根节点的值
inorder_traversal(root.right) # 遍历右子树
# 递归后序遍历
def postorder_traversal(root):
if not root:
return
postorder_traversal(root.left) # 遍历左子树
postorder_traversal(root.right) # 遍历右子树
print(root.val) # 先输出根节点的值
```
广度遍历(层次遍历)代码:
```python
from collections import deque
# 广度遍历(层次遍历)
def levelorder_traversal(root):
if not root:
return
q = deque()
q.append(root)
while q:
n = len(q)
for i in range(n):
node = q.popleft()
print(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
```
希望能够帮到你!
阅读全文