Simplify the python code of bst and avl tree.

This commit is contained in:
krahets 2023-06-30 05:17:30 +08:00
parent 98e797f1fc
commit ba481cb8e6
4 changed files with 9 additions and 17 deletions

View file

@ -15,11 +15,7 @@ class AVLTree:
def __init__(self, root: TreeNode | None = None):
"""构造方法"""
self.__root = root
@property
def root(self) -> TreeNode | None:
return self.__root
self.root = root
def height(self, node: TreeNode | None) -> int:
"""获取节点高度"""
@ -94,7 +90,7 @@ class AVLTree:
def insert(self, val) -> None:
"""插入节点"""
self.__root = self.__insert_helper(self.__root, val)
self.root = self.__insert_helper(self.root, val)
def __insert_helper(self, node: TreeNode | None, val: int) -> TreeNode:
"""递归插入节点(辅助方法)"""
@ -115,7 +111,7 @@ class AVLTree:
def remove(self, val: int) -> None:
"""删除节点"""
self.__root = self.__remove_helper(self.__root, val)
self.root = self.__remove_helper(self.root, val)
def __remove_helper(self, node: TreeNode | None, val: int) -> TreeNode | None:
"""递归删除节点(辅助方法)"""
@ -149,7 +145,7 @@ class AVLTree:
def search(self, val: int) -> TreeNode | None:
"""查找节点"""
cur = self.__root
cur = self.root
# 循环查找,越过叶节点后跳出
while cur is not None:
# 目标节点在 cur 的右子树中

View file

@ -16,7 +16,7 @@ class BinarySearchTree:
def __init__(self, nums: list[int]) -> None:
"""构造方法"""
nums.sort()
self.__root = self.build_tree(nums, 0, len(nums) - 1)
self.root = self.build_tree(nums, 0, len(nums) - 1)
def build_tree(
self, nums: list[int], start_index: int, end_index: int
@ -37,10 +37,6 @@ class BinarySearchTree:
)
return root
@property
def root(self) -> TreeNode | None:
return self.__root
def search(self, num: int) -> TreeNode | None:
"""查找节点"""
cur: TreeNode | None = self.root
@ -119,7 +115,7 @@ class BinarySearchTree:
pre.right = child
else:
# 若删除节点为根节点,则重新指定根节点
self.__root = child
self.root = child
# 子节点数量 = 2
else:
# 获取中序遍历中 cur 的下一个节点

View file

@ -1,7 +1,7 @@
# 复杂度分析
# 复杂度
<div class="center-table" markdown>
![复杂度分析](../assets/covers/chapter_complexity_analysis.jpg){ width="70%" }
![复杂度](../assets/covers/chapter_complexity_analysis.jpg){ width="70%" }
</div>

View file

@ -1,4 +1,4 @@
# 数据结构简介
# 数据结构
<div class="center-table" markdown>