给LZ小写一段
#include <assert.h>
#include <stdio.h>
#define STACK_SIZE 100
typedef struct tagBiTreeNode
{
int nKey;
struct tagBiTreeNode *pLChild, *pRChild;
struct tagBiTreeNode *pParent;
} BI_TREE_NODE, *PBI_TREE_NODE;
int insert(const int& nKey, const PBI_TREE_NODE _pNode)
{
assert(_pNode);
PBI_TREE_NODE pNode = (PBI_TREE_NODE)_pNode;
int nFlag = 1, nRet = 0;
while(nFlag)
{
if(nKey > pNode->nKey)
{
if(pNode->pRChild)
pNode = pNode->pRChild;
else
{
pNode->pRChild = new BI_TREE_NODE;
assert(pNode->pRChild);
pNode->pRChild->pParent = pNode;
pNode = pNode->pRChild;
pNode->nKey = nKey;
pNode->pLChild = NULL;
pNode->pRChild = NULL;
nFlag = 0;
}
}
else if(nKey < pNode->nKey)
{
if(pNode->pLChild)
pNode = pNode->pLChild;
else
{
pNode->pLChild = new BI_TREE_NODE;
assert(pNode->pLChild);
pNode->pLChild->pParent = pNode;
pNode = pNode->pLChild;
pNode->nKey = nKey;
pNode->pLChild = NULL;
pNode->pRChild = NULL;
nFlag = 0;
}
}
else
{
nFlag = 0;
nRet = 1;
}
}
return nRet;
}
void dispose(PBI_TREE_NODE pRoot)
{
PBI_TREE_NODE pStack[STACK_SIZE];
int nTop = -1;
pStack[++nTop] = pRoot;
while(nTop >= 0)
{
PBI_TREE_NODE pNode = pStack[nTop--];
if(pNode)
{
pStack[++nTop] = pNode->pLChild;
pStack[++nTop] = pNode->pRChild;
}
delete pNode;
}
}
void preorder(PBI_TREE_NODE pNode)
{
if(pNode)
{
printf("%3d", pNode->nKey);
preorder(pNode->pLChild);
preorder(pNode->pRChild);
}
}
int main(int argc, char* argv[])
{
int arrKey[10] = {1,2,3,4,4,5,6,7,8,9};
PBI_TREE_NODE pRoot = new BI_TREE_NODE;
assert(pRoot);
// insert the first node
pRoot->nKey = arrKey[0];
pRoot->pLChild = NULL;
pRoot->pRChild = NULL;
pRoot->pParent = NULL;
for(int i = 1; i < 10; i++)
{
if(insert(arrKey[i], pRoot))
{
printf("The key = %d is already exist!\n", arrKey[i]);
}
}
// sorted result
preorder(pRoot);
printf("\n");
// dispose
dispose(pRoot);
pRoot = NULL;
return 0;
}