C++与Rust混合调试实战:三步实现无缝断点与40%性能提升
2026/8/10 8:14:27
一、二叉排序树的插入特性
二、二叉排序树的删除操作
根据被删除结点*p的结构,分为三种情况处理:
p是叶子结点(且非根)
p只有左子树或只有右子树
f->lchild = p->rchild。p同时有左、右子树
补充:二叉排序树的核心作用
// 示例:二叉排序树节点定义structTreeNode{intval;structTreeNode*left;structTreeNode*right;};在二叉排序树(BST)中,中序后继是指中序遍历序列中紧跟在指定节点之后的节点。实现中序后继查找需根据节点是否有右子树来分情况处理:
若目标节点p有右子树,则其中序后继是其右子树中的最左节点(即右子树中值最小的节点)。
步骤:
p->right。left为空。structTreeNode*findInorderSuccessor(structTreeNode*p){structTreeNode*current=p->right;while(current&¤t->left!=NULL){current=current->left;}returncurrent;}若p没有右子树,则中序后继在其祖先中寻找:从根开始向下搜索,找到第一个“大于p->val”且“左子树包含p”的祖先节点。
方法:从根出发,用一个指针追踪可能的后继。
structTreeNode*findInorderSuccessorFromRoot(structTreeNode*root,structTreeNode*p){structTreeNode*successor=NULL;while(root!=NULL){if(p->val<root->val){successor=root;// 当前根可能是后继root=root->left;}else{root=root->right;}}returnsuccessor;}注意:此方法适用于没有父指针的树结构。
如果每个节点含有指向父节点的指针(parent),可以向上回溯:
p是其父节点的左孩子 → 父节点就是后继。structTreeNode*findInorderSuccessorWithParent(structTreeNode*p){if(p->right){// 有右子树:找右子树中最左节点structTreeNode*current=p->right;while(current->left){current=current->left;}returncurrent;}else{// 无右子树:向上找第一个左分支的祖先structTreeNode*current=p;structTreeNode*parent=current->parent;while(parent!=NULL&¤t==parent->right){current=parent;parent=parent->parent;}returnparent;}}| 条件 | 中序后继 |
|---|---|
| 有右子树 | 右子树的最左节点 |
| 无右子树 | 第一个“左子树包含该节点”的祖先 |
时间复杂度:O(h),h为树高;理想情况下 O(log n),最坏 O(n)。