Idea:

BST là cấu trúc cây nhị phân nơi:


🔹 Cấu trúc Node:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

🔹 Search

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


🔹 Insert

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


🔹 Remove

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


🔹 Example Usage

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)