Idea:
BST là cấu trúc cây nhị phân nơi:
Node trái < root
Node phải > root
→ Cho phép tìm kiếm, chèn, xóa nhanh O(log n) nếu cây cân bằng.
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def search(root, target):
if not root:
return False
if target > root.val:
return search(root.right, target)
elif target < root.val:
return search(root.left, target)
else:
return True
def insert(root, val):
if not root:
return TreeNode(val)
if val > root.val:
root.right = insert(root.right, val)
elif val < root.val:
root.left = insert(root.left, val)
return root
def minValueNode(root):
curr = root
while curr.left:
curr = curr.left
return curr
def remove(root, val):
if not root:
return None
if val > root.val:
root.right = remove(root.right, val)
elif val < root.val:
root.left = remove(root.left, val)
else:
# Node có 0 hoặc 1 con
if not root.left:
return root.right
elif not root.right:
return root.left
# Node có 2 con → tìm successor (min của cây phải)
minNode = minValueNode(root.right)
root.val = minNode.val
root.right = remove(root.right, minNode.val)
return root
root = TreeNode(4)
insert(root, 2)
insert(root, 5)
insert(root, 1)
insert(root, 3)
print(search(root, 5)) # True
print(search(root, 6)) # False
remove(root, 2)