为什么要左旋右旋?
为了使得左右子树的高度差在一定范围内,需要通过旋转调整,这样就可以保持平稳的搜索效率
左旋:
步骤
1.设原来E的父节点是father,那么左旋之后需要改变的是:
2.S和father的关系(若无father则不需要)
3.S和E的关系
4.E和between E and S的关系
实现代码:
void tree::L_rotate(node *p)
{node* father = p->p_parent;node* pr = p->p_Rchild;node* prl = pr->p_Lchild;if(p == root){// p and prpr->p_Lchild = p;p->p_parent = pr;// p and prlif(prl != nullptr){p->p_Rchild = prl;prl->p_parent = p;}elsep->p_Rchild = nullptr;// pr is rootpr->p_parent = nullptr;root = pr;}else{// father and prif(father->p_Rchild == p)father->p_Rchild = pr;elsefather->p_Lchild = pr;pr->p_parent = father;// p and prpr->p_Lchild = p;p->p_parent = pr;// p and prlif(prl != nullptr){p->p_Rchild = prl;prl->p_parent = p;}elsep->p_Rchild = nullptr;}
}
右旋:
步骤与左旋对称,不再赘述
实现代码:
void tree::R_rotate(node *p)
{node* father = p->p_parent;node* pl = p->p_Lchild;node* plr = pl->p_Rchild;if(p == root){// p and plpl->p_Rchild = p;p->p_parent = pl;// p and plrif(plr != nullptr){p->p_Lchild = plr;plr->p_parent = p;}elsep->p_Lchild = nullptr;// pl is rootpl->p_parent = nullptr;root = pl;}else{// father and plif(father->p_Rchild == p)father->p_Rchild = pl;elsefather->p_Lchild = pl;pl->p_parent = father;//p and plpl->p_Rchild = p;p->p_parent = pl;// p and plrif(plr != nullptr){p->p_Lchild = plr;plr->p_parent = p;}elsep->p_Lchild = nullptr;}
}