二叉搜索树
逐个插入数值构建二叉搜索树。观察树的形状如何依赖插入顺序,以及查找、中序遍历和退化的过程。
7 分钟难度 2/3交互演示区域不展示广告。
Nodes9Height4BalanceBalancedBest height4
In-order
20 · 30 · 35 · 40 · 50 · 60 · 65 · 70 · 80Insert a value to grow the tree.
Insert values in different orders, then use Search to highlight the comparison path. Sorted input such as 10, 20, 30, 40 turns the tree into a linked list, so the balance panel reports Skewed and the height approaches the node count. Balanced insertion keeps the height near log₂ n.
你看到的是什么
1
每个节点最多有两个子节点。左子树的值更小,右子树的值更大。
2
插入时从根节点向下比较,把新值挂到第一个空位置。
3
中序遍历先访问左子树,再访问节点,最后访问右子树,输出恰好是有序的。
为什么重要
二叉搜索树是有序映射、数据库和大量面试题的基础。它也说明了平衡树的必要性:糟糕的插入顺序会把 O(log n) 变成 O(n)。
复杂度与细节
平均查找/插入:O(log n)。最坏情况(退化树):O(n)。空间:O(n)。
常见问题
为什么插入顺序很重要?+
平衡树的高度接近 log n。把有序数据插入普通 BST 会形成链表,操作退化为线性。
平衡树如何解决这个问题?+
AVL 树和红黑树会在插入、删除后旋转节点,把树高维持在 O(log n)。