二叉树代码
时间: 2023-07-03 13:22:12 浏览: 95
下面是一个简单的二叉树的代码实现,包括创建二叉树、遍历二叉树(前序遍历、中序遍历、后序遍历):
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 创建二叉树
def create_binary_tree(arr):
if not arr:
return None
root = TreeNode(arr[0])
node_queue = [root]
front = 0
index = 1
while index < len(arr):
node = node_queue[front]
front += 1
item = arr[index]
index += 1
if item is not None:
node.left = TreeNode(item)
node_queue.append(node.left)
if index >= len(arr):
break
item = arr[index]
index += 1
if item is not None:
node.right = TreeNode(item)
node_queue.append(node.right)
return root
# 前序遍历二叉树
def preorder_traversal(root):
if not root:
return
print(root.val, end=' ')
preorder_traversal(root.left)
preorder_traversal(root.right)
# 中序遍历二叉树
def inorder_traversal(root):
if not root:
return
inorder_traversal(root.left)
print(root.val, end=' ')
inorder_traversal(root.right)
# 后序遍历二叉树
def postorder_traversal(root):
if not root:
return
postorder_traversal(root.left)
postorder_traversal(root.right)
print(root.val, end=' ')
```
使用示例:
```python
# 创建一个二叉树
arr = [1, 2, 3, None, None, 4, None, None, 5, None, 6]
root = create_binary_tree(arr)
# 前序遍历二叉树
preorder_traversal(root) # 1 2 3 4 5 6
# 中序遍历二叉树
inorder_traversal(root) # 2 1 4 3 5 6
# 后序遍历二叉树
postorder_traversal(root) # 2 4 6 5 3 1
```
阅读全文