python二叉树函数
时间: 2023-12-07 21:03:45 浏览: 85
以下是一个用 Python 实现二叉树操作的示例函数```python
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return TreeNode(value)
else:
if value < root.val:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
def search(root, value):
if root is None or root.val == value:
return root
if value < root.val:
return search(root.left, value)
return search(root.right, value)
def delete(root, value):
if root is None:
return root
if value < root.val:
root.left = delete(root.left, value)
elif value > root.val:
root.right = delete(root.right, value)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.val = temp.val
root.right = delete(root.right, temp.val)
return root
def minValueNode(node):
current = node
while current.left is not None:
current = current.left
return current
def inorderTraversal(root):
if root is not None:
inorderTraversal(root.left)
print(root.val, end=' ')
inorderTraversal(root.right)
```
这些函数实现了二叉树的基本操作,包括插入节点、搜索节点、删除节点和中序遍历等。你可以根据需要使用这些函数来操作二叉树。
阅读全文