数据结构二叉树的基本操作
时间: 2023-11-12 14:09:03 浏览: 90
数据结构-实验五讲义(1)-二叉树的基本操作.docx
以下是二叉树的基本操作:
1.创建二叉树
```python
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def create_tree():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
return root
```
2.遍历二叉树
- 前序遍历
```python
def preorder_traversal(root):
if root:
print(root.val)
preorder_traversal(root.left)
preorder_traversal(root.right)
```
- 中序遍历
```python
def inorder_traversal(root):
if root:
inorder_traversal(root.left)
print(root.val)
inorder_traversal(root.right)
```
- 后序遍历
```python
def postorder_traversal(root):
if root:
postorder_traversal(root.left)
postorder_traversal(root.right)
print(root.val)
```
3.查找二叉树中的节点
```python
def find_node(root, val):
if not root:
return None
if root.val == val:
return root
left = find_node(root.left, val)
if left:
return left
right = find_node(root.right, val)
if right:
return right
return None
```
阅读全文