Python 二叉树代码实现及示例 - 数据结构算法
二叉树是一种常见的数据结构,它是一种树形结构,其中每个节点最多有两个子节点,通常称为左子树和右子树。
下面是一个简单的二叉树的实现代码,包括节点定义和基本操作,如插入、删除和遍历等。
# 定义二叉树节点
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 插入节点
def insert(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
# 删除节点
def delete(root, val):
if not root:
return root
if val < root.val:
root.left = delete(root.left, val)
elif val > root.val:
root.right = delete(root.right, val)
else:
if not root.left:
return root.right
if not root.right:
return root.left
temp = root.right
mini = temp.val
while temp.left:
temp = temp.left
mini = temp.val
root.val = mini
root.right = delete(root.right, mini)
return root
# 先序遍历
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
# 中序遍历
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
# 后序遍历
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
使用示例:
root = None
root = insert(root, 5)
root = insert(root, 3)
root = insert(root, 7)
root = insert(root, 1)
root = insert(root, 9)
print('先序遍历:')
preorder(root)
print('中序遍历:')
inorder(root)
print('后序遍历:')
postorder(root)
root = delete(root, 3)
print('删除节点3后:')
inorder(root)
输出结果:
先序遍历:
5
3
1
7
9
中序遍历:
1
3
5
7
9
后序遍历:
1
3
9
7
5
删除节点3后:
1
5
7
9
原文地址: http://www.cveoy.top/t/topic/nQRc 著作权归作者所有。请勿转载和采集!