二叉树插入,查找,删除节点Python代码举例
时间: 2023-11-19 14:23:33 浏览: 103
python实现二叉查找树实例代码
以下是 Python 实现的二叉树插入、查找和删除节点的代码示例:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
# 插入节点
def insert(self, val):
if not self.root:
self.root = Node(val)
else:
self._insert(val, self.root)
def _insert(self, val, node):
if val < node.val:
if node.left:
self._insert(val, node.left)
else:
node.left = Node(val)
else:
if node.right:
self._insert(val, node.right)
else:
node.right = Node(val)
# 查找节点
def search(self, val):
if not self.root:
return False
else:
return self._search(val, self.root)
def _search(self, val, node):
if not node:
return False
elif node.val == val:
return True
elif val < node.val:
return self._search(val, node.left)
else:
return self._search(val, node.right)
# 删除节点
def delete(self, val):
if not self.root:
return False
else:
self.root = self._delete(val, self.root)
def _delete(self, val, node):
if not node:
return node
elif val < node.val:
node.left = self._delete(val, node.left)
elif val > node.val:
node.right = self._delete(val, node.right)
else:
if not node.left:
return node.right
elif not node.right:
return node.left
else:
temp = self._find_min(node.right)
node.val = temp.val
node.right = self._delete(temp.val, node.right)
return node
def _find_min(self, node):
while node.left:
node = node.left
return node
```
以上是二叉树的基本操作,具体使用方式可以参考以下示例:
```python
bt = BinaryTree()
# 插入节点
bt.insert(5)
bt.insert(3)
bt.insert(7)
bt.insert(1)
bt.insert(9)
# 查找节点
print(bt.search(7)) # True
print(bt.search(4)) # False
# 删除节点
bt.delete(3)
print(bt.search(3)) # False
```
阅读全文