看了 程序抽象思想 里面写了部分代码,但是想把它补全,表示很蛋疼!
有问题:
#include "stdio.h"
#include <string>
struct nodeT
{
nodeT()
: pLeft(NULL)
, pRight(NULL)
, bf(0)
{
}
std::string key;
nodeT* pLeft;
nodeT* pRight;
int bf;
};
void RotateLeft(nodeT*& pTree)
{
nodeT* pParent = pTree;
nodeT* pClild = pParent->pRight;
pParent->pRight = pClild->pLeft;
pClild->pLeft = pParent;
pTree = pClild;
}
void RotateRight(nodeT*& pTree)
{
nodeT* pParent = pTree;
nodeT* pClild = pParent->pLeft;
pParent->pLeft = pClild->pRight;
pClild->pRight = pParent;
pTree = pClild;
}
void FixLeftBalance(nodeT* pTree)
{
nodeT* pParent = pTree;
nodeT* cptr = pParent->pLeft;
nodeT* pChind = cptr;
int oldBf = 0;
if (pChind->bf != pParent->bf)
{
oldBf = pChind->pRight->bf;
RotateLeft(cptr);
RotateRight(pTree);
nodeT* t = pTree;
t->bf = 0;
switch(oldBf)
{
case -1:
{
t->pLeft->bf = 0;
t->pRight->bf = 1;
break;
}
case 1:
{
t->pLeft->bf = -1;
t->pRight->bf = 0;
break;
}
case 0:
{
t->pLeft->bf= 0;
t->pRight->bf = 0;
break;
}
}
}
else
{
RotateRight(pTree);
nodeT* t = pTree;
t->pRight->bf = 0;
t->bf = 0;
}
}
void FixRightBalance(nodeT*& pTree)
{
nodeT* pParent = pTree;
nodeT* cptr = pParent->pRight;
nodeT* pChind = cptr;
int oldBf = 0;
if (pChind->bf != pParent->bf)
{
oldBf = pChind->pLeft->bf;
RotateRight(cptr);
RotateLeft(pTree);
nodeT* t = pTree;
t->bf = 0;
switch(oldBf)
{
case -1:
{
t->pRight->bf = 0;
t->pLeft->bf = 1;
break;
}
case 1:
{
t->pRight->bf = -1;
t->pLeft->bf = 0;
break;
}
case 0:
{
t->pRight->bf= 0;
t->pLeft->bf = 0;
break;
}
}
}
else
{
RotateLeft(pTree);
nodeT* t = pTree;
t->pLeft->bf = 0;
t->bf = 0;
}
}
int InsertNode(nodeT*& pTree, std::string key)
{
if (NULL == pTree)
{
pTree = new nodeT;
pTree->key = key;
return 1;
}
int sign = key.compare(pTree->key);
if (0 == sign)
{
return 0;
}
int delta = 0;
if (sign < 0)
{
delta = InsertNode(pTree->pLeft,key);
if (0 == delta)
{
return 0;
}
switch(pTree->bf)
{
case 1:
{
pTree->bf = 0;
return 0;
}
case 0:
{
pTree->bf = -1;
return 1;
}
case -1:
{
FixLeftBalance(pTree);
return 0;
}
}
}
else
{
delta = InsertNode(pTree->pRight,key);
if (0 == delta)
{
return 0;
}
switch(pTree->bf)
{
case -1:
{
pTree->bf = 0;
return 0;
}
case 0:
{
pTree->bf = 1;
return 1;
}
case 1:
{
FixRightBalance(pTree);
return 0;
}
}
}
}
void PrintfTree(nodeT* pTree)
{
if (NULL != pTree)
{
PrintfTree(pTree->pLeft);
printf("%s ", pTree->key.c_str());
PrintfTree(pTree->pRight);
}
}
int main()
{
nodeT* pTree = NULL;
InsertNode(pTree, "1");
InsertNode(pTree, "2");
InsertNode(pTree, "111");
InsertNode(pTree, "3");
InsertNode(pTree, "4");
InsertNode(pTree, "5");
InsertNode(pTree, "-1");
PrintfTree(pTree);
}