AVL树查找算法时间复杂度
时间: 2024-01-29 19:09:37 浏览: 111
AVL树是一种自平衡的二叉搜索树,它的查找算法时间复杂度为O(log n),其中n是树中节点的数量。
AVL树通过在插入或删除节点时进行旋转操作来保持树的平衡性。在AVL树中,每个节点都有一个平衡因子,它表示该节点的左子树高度与右子树高度之差。当插入或删除节点后,如果某个节点的平衡因子超过了1或-1,就需要进行旋转操作来恢复平衡。
由于AVL树保持了树的平衡性,所以在最坏情况下,AVL树的高度为O(log n)。因此,查找操作的时间复杂度为O(log n)。
下面是一个AVL树的查找算法的示例代码:
```python
class Node:
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, root, key):
if root is None:
return Node(key)
elif key < root.key:
root.left = self._insert(root.left, key)
else:
root.right = self._insert(root.right, key)
root.height = 1 + max(self._get_height(root.left), self._get_height(root.right))
balance = self._get_balance(root)
if balance > 1 and key < root.left.key:
return self._rotate_right(root)
if balance < -1 and key > root.right.key:
return self._rotate_left(root)
if balance > 1 and key > root.left.key:
root.left = self._rotate_left(root.left)
return self._rotate_right(root)
if balance < -1 and key < root.right.key:
root.right = self._rotate_right(root.right)
return self._rotate_left(root)
return root
def _get_height(self, root):
if root is None:
return 0
return root.height
def _get_balance(self, root):
if root is None:
return 0
return self._get_height(root.left) - self._get_height(root.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
def search(self, key):
return self._search(self.root, key)
def _search(self, root, key):
if root is None or root.key == key:
return root
if key < root.key:
return self._search(root.left, key)
return self._search(root.right, key)
```
阅读全文