在Python中實(shí)現(xiàn)AVL樹,需要定義一個(gè)TreeNode類來(lái)表示樹的節(jié)點(diǎn),然后定義一個(gè)AVLTree類來(lái)實(shí)現(xiàn)AVL樹的操作。
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree:
def __init__(self):
self.root = None
def insert(self, key):
self.root = self._insert(self.root, key)
def _insert(self, node, key):
if not node:
return TreeNode(key)
if key < node.key:
node.left = self._insert(node.left, key)
else:
node.right = self._insert(node.right, key)
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
balance = self._get_balance(node)
# 左旋
if balance > 1 and key < node.left.key:
return self._rotate_right(node)
# 右旋
if balance < -1 and key > node.right.key:
return self._rotate_left(node)
# 左右旋
if balance > 1 and key > node.left.key:
node.left = self._rotate_left(node.left)
return self._rotate_right(node)
# 右左旋
if balance < -1 and key < node.right.key:
node.right = self._rotate_right(node.right)
return self._rotate_left(node)
return node
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)
def _rotate_left(self, z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self._get_height(z.left), self._get_height(z.right))
y.height = 1 + max(self._get_height(y.left), self._get_height(y.right))
return y
def _rotate_right(self, z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self._get_height(z.left), self._get_height(z.right))
y.height = 1 + max(self._get_height(y.left), self._get_height(y.right))
return y
以上是AVL樹的Python實(shí)現(xiàn)代碼,包括了插入節(jié)點(diǎn)和旋轉(zhuǎn)操作。可以根據(jù)需要進(jìn)一步實(shí)現(xiàn)刪除節(jié)點(diǎn)、查找節(jié)點(diǎn)等操作。