#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Infor
{
int nNum;
struct Infor *lChild, *rChild, *next;
};
class Test
{
public:
Test();
void creatTree();
void PreTree();
void MidTree();
void LastTree();
void LevelTree();
void LevelTrees(struct Infor *p);
bool IsEmpty();
void BuildQueue(struct Infor *p);
struct Infor * OutQueue();
private:
struct Infor *Root;
struct Infor *m_pHead, *m_pTail, m_array[4];
int m_nSum;
};
Test::Test()
{
Root = NULL;
m_pHead = m_pTail = new struct Infor; //建立一个循环队列
m_pTail->next = NULL;
}
static int creat(struct Infor *p, int k)
{
struct Infor *q = NULL;
int i;
cin >> i;
if (0 != i)
{
q = new struct Infor;
q->nNum = i;
q->lChild = NULL;
q->rChild = NULL;
if (1 == k)
{
p->lChild = q;
}
if (2 == k)
{
p->rChild = q;
}
creat(q, 1);
creat(q, 2);
}
return 0;
}
void Test::creatTree()
{
int i;
struct Infor *p = NULL;
cin >> i;
if (0 == i)
{
return;
}
p = new struct Infor;
p->nNum = i;
p->lChild = NULL;
p->rChild = NULL;
Root = p;
creat(p, 1);
creat(p, 2);
return;
}
static int PreTrees(struct Infor *p)
{
if (NULL != p)
{
cout << p->nNum << " ";
PreTrees(p->lChild);
PreTrees(p->rChild);
}
return 0;
}
void Test::PreTree()
{
struct Infor *p = NULL;
p = Root;
PreTrees(p);
cout << endl;
}
static int MidTrees(struct Infor *p)
{
if (NULL != p)
{
MidTrees(p->lChild);
cout << p->nNum << " ";
MidTrees(p->rChild);
}
return 0;
}
void Test::MidTree()
{
struct Infor *p = NULL;
p = Root;
MidTrees(p);
cout << endl;
}
static int LastTrees(struct Infor *p)
{
if (NULL != p)
{
LastTrees(p->lChild);
LastTrees(p->rChild);
cout << p->nNum << " ";
}
return 0;
}
void Test::LastTree()
{
struct Infor *p = NULL;
p = Root;
LastTrees(p);
cout << endl;
}
struct Infor * Test::OutQueue()
{
struct Infor *temp;
temp = m_pHead->next;
m_pHead->next = m_pHead->next->next;
return temp;
}
void Test::BuildQueue(struct Infor *p)
{
m_pTail->next = p;
m_pTail = p;
}
bool Test::IsEmpty()
{
bool bRet = false;
if (m_pHead == m_pTail)
{
bRet = true;
}
return bRet;
}
void Test::LevelTrees(struct Infor *p)
{
const int MaxSize = 100;
int front = 0;
int rear = 0; //采用顺序队列,并假定不会发生上溢
struct Infor * Q[MaxSize];
struct Infor * q;
if (p==NULL)
return;
else
{
Q[rear++] = p;
while (front != rear)
{
q = Q[front++];
cout<<q->nNum<<" ";
if (q->lChild != NULL)
{
Q[rear++] = q->lChild;
}
if (q->rChild != NULL)
{
Q[rear++] = q->rChild;
}
}
}
}
void Test::LevelTree()
{
struct Infor *p = NULL;
p = Root;
LevelTrees(p);
cout << endl;
}
int main()
{
// freopen("1.txt", "r", stdin);
Test t1;
t1.creatTree();
t1.PreTree();
t1.MidTree();
t1.LastTree();
t1.LevelTree();
return 0;
}