红黑树 实现 研究

#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);
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：红黑树 实现 研究 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)