蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验有序数组二分查找、BST 全局有序不变式与数组复杂度对比

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-binary-search-tree.py
explore-binary-search-tree.py164 行
"""Offline algorithm verification lab for Chapter 27 (binary-search-tree)."""
import json

VERSION = "CPython 3.12.14 offline DSA verifier (binary-search-tree)"


def binary_search(arr: list, target) -> tuple:
    """Iterative binary search using mid = l + (r - l) // 2; returns (index, steps)."""
    l, r = 0, len(arr) - 1
    steps = 0
    while l <= r:
        steps += 1
        mid = l + (r - l) // 2
        if arr[mid] == target:
            return mid, steps
        if arr[mid] > target:
            r = mid - 1
        else:
            l = mid + 1
    return -1, steps


class BSTNode:
    def __init__(self, key, value=None, left=None, right=None):
        self.key = key
        self.value = value
        self.left = left
        self.right = right


def is_valid_bst(node, low=None, high=None) -> bool:
    if node is None:
        return True
    if low is not None and node.key <= low:
        return False
    if high is not None and node.key >= high:
        return False
    return is_valid_bst(node.left, low, node.key) and is_valid_bst(node.right, node.key, high)


def case_binary_search_array_lookup():
    arr = [3, 8, 14, 21, 29, 36, 42, 55, 68, 77, 91]
    idx_first, s1 = binary_search(arr, 3)
    idx_mid, s2 = binary_search(arr, 36)
    idx_last, s3 = binary_search(arr, 91)
    idx_miss, s4 = binary_search(arr, 50)
    idx_empty, s5 = binary_search([], 10)
    expected = {
        "found_first": 0,
        "found_mid": 5,
        "found_last": 10,
        "miss": -1,
        "empty": -1,
        "max_steps_within_log2_plus_1": True,
    }
    actual = {
        "found_first": idx_first,
        "found_mid": idx_mid,
        "found_last": idx_last,
        "miss": idx_miss,
        "empty": idx_empty,
        "max_steps_within_log2_plus_1": max(s1, s2, s3, s4, s5) <= 4,
    }
    return {
        "name": "binary_search_array_lookup",
        "summary": "验证有序数组二分查找(mid = l + (r-l)//2 防溢出写法)对首/中/尾元素、未命中与空数组的返回及对数步数上界",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bst_property_validation():
    # Valid BST: 41 as root, left (22 -> 15, 33), right (58 -> 50, 63)
    valid_root = BSTNode(
        41,
        left=BSTNode(22, left=BSTNode(15), right=BSTNode(33)),
        right=BSTNode(58, left=BSTNode(50), right=BSTNode(63)),
    )
    # Invalid BST: right subtree contains 38 < root 41 even though 38 < 58
    invalid_root = BSTNode(
        41,
        left=BSTNode(22, left=BSTNode(15), right=BSTNode(33)),
        right=BSTNode(58, left=BSTNode(38), right=BSTNode(63)),
    )
    expected = {"valid_bst_accepted": True, "subtree_violation_rejected": True}
    actual = {
        "valid_bst_accepted": is_valid_bst(valid_root),
        "subtree_violation_rejected": not is_valid_bst(invalid_root),
    }
    return {
        "name": "bst_property_validation",
        "summary": "校验二分搜索树全局子树约束:左子树所有节点小于根、右子树所有节点大于根,拒绝仅满足局部父子关系的伪 BST",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_array_vs_bst_complexity_profile():
    # Build balanced 63-node BST (height 6) vs ordinary array and sorted array
    def build_balanced(nums):
        if not nums:
            return None
        mid = len(nums) // 2
        return BSTNode(nums[mid], left=build_balanced(nums[:mid]), right=build_balanced(nums[mid + 1 :]))

    keys = list(range(1, 64))
    root = build_balanced(keys)
    # Measure search steps for target=62
    target = 62
    linear_steps = 0
    for x in keys:
        linear_steps += 1
        if x == target:
            break
    _, bin_steps = binary_search(keys, target)

    bst_steps = 0
    cur = root
    while cur is not None:
        bst_steps += 1
        if cur.key == target:
            break
        cur = cur.left if target < cur.key else cur.right

    # Sorted array insertion at head requires shifting n elements
    sorted_insert_shifts = len(keys)

    expected = {
        "linear_steps": 62,
        "binary_search_steps_le_6": True,
        "bst_search_steps_le_6": True,
        "sorted_array_head_insert_shifts": 63,
        "bst_balanced_valid": True,
    }
    actual = {
        "linear_steps": linear_steps,
        "binary_search_steps_le_6": bin_steps <= 6,
        "bst_search_steps_le_6": bst_steps <= 6,
        "sorted_array_head_insert_shifts": sorted_insert_shifts,
        "bst_balanced_valid": is_valid_bst(root),
    }
    return {
        "name": "array_vs_bst_complexity_profile",
        "summary": "对比普通数组、顺序数组与平衡二分搜索树(63 节点)在查找与插入开销上的差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_binary_search_array_lookup(),
        case_bst_property_validation(),
        case_array_vs_bst_complexity_profile(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。

入口文件:projects/data-structures-binary-search-tree-lab/explore-binary-search-tree.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-binary-search-tree.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2646.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习