随便写的,别见怪……
#include
#include
using namespace std;
#define MAX_TREE_NODE 10
struct Node
{
int elem;
struct Node *pLeft , *pRight;
bool bVisit;
Node() : elem(0) , pLeft(NULL) , pRight(NULL) , bVisit(false)
{
}
};
void BuildTree(struct Node **pTree)
{
if (pTree == NULL)
{
return ;
}
for ( int i = 0; i < MAX_TREE_NODE; ++i )
{
struct Node *pElem = new Node;
if (pElem == NULL)
{
continue;
}
coutpElem->elem;
if (*pTree == NULL)
{
*pTree = pElem;
}
else
{
Node *pCompare = *pTree;
while( pCompare != NULL)
{
if ( pElem->elem > pCompare->elem )
{
if (pCompare->pRight != NULL)
{
pCompare = pCompare->pRight;
}
else
{
pCompare->pRight = pElem;
break;
}
}
else
{
if (pCompare->pLeft != NULL)
{
pCompare = pCompare->pLeft;
}
else
{
pCompare->pLeft = pElem;
break;
}
}
}
}
}
}
//把整个树标记成未访问状态 防止访问完再次访问时出现无法访问
void MakeTreeUnVisit(struct Node *pTree)
{
stack s;
s.push( pTree );
while ( !s.empty() )
{
struct Node *pVisit = s.top();
s.pop();
if ( pVisit )
{
pVisit->bVisit = false;
s.push( pVisit->pRight );
s.push( pVisit->pLeft );
}
}
}
//前序 根-左-右
void PrintTree_1(struct Node *pTree)
{
stack s;
s.push( pTree );
while ( !s.empty() )
{
struct Node *pVisit = s.top();
s.pop();
if ( pVisit )
{
coutpLeft ); //左
pVisit->bVisit = true;
}
}
}
coutpRight );
s.push( pVisit );
s.push( pVisit->pLeft );
pVisit->bVisit = true;
}
else
{
cout |