平衡二叉树的旋转(左旋和右旋)
右旋:
void RightSpin(Tree** ppTree) { Tree* pTree = *ppTree; Tree* ptmp = pTree->pleft; pTree->pleft = ptmp->pright; if(ptmp->pright) ptmp->pright->pFather = pTree; ptmp->pright = pTree; ptmp->pFather = pTree->pFather; if(pTree->pFather) {printf("----\n"); if(pTree == pTree->pFather->pright) pTree->pFather->pright = ptmp; else pTree->pFather->pleft = ptmp; } else *ppTree = ptmp; pTree->pFather = ptmp; }
左旋:
void LeftSpin(Tree** ppTree) { Tree* pTree = *ppTree; Tree* ptmp = pTree->pright; pTree->pright = ptmp->pleft; if(ptmp->pleft) ptmp->pleft->pFather = pTree; ptmp->pleft = pTree; ptmp->pFather = pTree->pFather; if(pTree->pFather) { if(pTree == pTree->pFather->pright) pTree->pFather->pright = ptmp; else pTree->pFather->pleft = ptmp; } else *ppTree = ptmp; pTree->pFather = ptmp; }
感谢某人的debug:ptmp->pFather 指针,无论pTree是否有根节点都要 = pTree->pFather;(没有是赋为空)