用Python写一个平衡二叉树
时间: 2023-04-05 13:02:34 浏览: 118
非常感谢您的提问,我可以回答这个问题。平衡二叉树是一种特殊的二叉搜索树,它的左右子树的高度差不超过1。在Python中,可以使用类来实现平衡二叉树。具体实现方法可以参考以下代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
class AVLTree:
def __init__(self):
self.root = None
def insert(self, val):
self.root = self._insert(self.root, val)
def _insert(self, node, val):
if not node:
return TreeNode(val)
elif val < node.val:
node.left = self._insert(node.left, val)
else:
node.right = self._insert(node.right, val)
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
balance = self._get_balance(node)
if balance > 1 and val < node.left.val:
return self._right_rotate(node)
if balance < -1 and val > node.right.val:
return self._left_rotate(node)
if balance > 1 and val > node.left.val:
node.left = self._left_rotate(node.left)
return self._right_rotate(node)
if balance < -1 and val < node.right.val:
node.right = self._right_rotate(node.right)
return self._left_rotate(node)
return node
def _left_rotate(self, node):
new_root = node.right
node.right = new_root.left
new_root.left = node
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
new_root.height = 1 + max(self._get_height(new_root.left), self._get_height(new_root.right))
return new_root
def _right_rotate(self, node):
new_root = node.left
node.left = new_root.right
new_root.right = node
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
new_root.height = 1 + max(self._get_height(new_root.left), self._get_height(new_root.right))
return new_root
def _get_height(self, node):
if not node:
return 0
return node.height
def _get_balance(self, node):
if not node:
return 0
return self._get_height(node.left) - self._get_height(node.right)
```
以上是一个简单的平衡二叉树的实现,可以通过调用`insert`方法来插入新的节点。
阅读全文