递归算法
先序
void PreOrder(BTNode* b)
{
if (b != NULL)
{
cout << b->data;
PreOrder(b->lchild);
PreOrder(b->rchild);
}
}
中序
void InOrder(BTNode* b)
{
if (b != NULL)
{
InOrder(b->lchild);
cout << b->data;
InOrder(b->rchild);
}
}
后序
void PostOrder(BTNode* b)
{
if (b != NULL)
{
PostOrder(b->lchild);
PostOrder(b->rchild);
cout << b->data;
}
}
非递归算法
先序
前置栈代码
typedef struct {
BTNode* data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack*& s)
{
s = (SqStack*)malloc(sizeof(SqStack));
s->top = -1;
}
void DestoyStack(SqStack*& s)
{
free(s);
}
bool StackEmpty(SqStack* s)
{
return (s->top == -1);
}
bool Push(SqStack*& s, BTNode* e)
{
if (s->top == MAXSIZE - 1)
return false;
s->top++;
s->data[s->top] = e;
return true;
}
bool Pop(SqStack*& s, BTNode*& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];
s->top--;
return true;
}
bool GetTop(SqStack* s, BTNode*& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];
return true;
}
void PreOrder1(BTNode* b)
{
BTNode* p;
SqStack *stack;
InitStack(stack);
if (b != NULL)
{
Push(stack, b);
while (!StackEmpty(stack))
{
Pop(stack, p);
cout << p->data;
if (p->rchild!= NULL)
Push(stack,p->rchild);
if (p->lchild != NULL)
Push(stack, p->lchild);
}
cout << endl;
}
DestoyStack(stack);
}
void PreOreder2(BTNode* b)
{
BTNode* p;
SqStack* stack;
InitStack(stack);
p = b;
while (!StackEmpty(stack) || p != NULL)
{
while (p != NULL)
{
cout << p->data;
Push(stack, p);
p = p->lchild;
}
if (!StackEmpty(stack))
{
Pop(stack, p);
p = p->rchild;
}
}
cout << endl;
DestoyStack(stack);
}
中序
void InOrder1(BTNode* b)
{
BTNode* p;
SqStack* stack;
InitStack(stack);
p = b;
while (!StackEmpty(stack) || p != NULL)
{
while (p != NULL)
{
Push(stack, p->lchild);
p = p->lchild;
}
if (!StackEmpty(stack))
{
Pop(stack, p);
cout << p->data;
p = p->rchild;
}
}
cout << endl;
DestoyStack(stack);
}
后序
void PostOrder1(BTNode* b)
{
BTNode* p, * r;
SqStack* stack;
InitStack(stack);
p = b;
bool flag;
do
{
while (p != NULL)
{
Push(stack, p);
p = p->lchild;
}
r = NULL;
flag = true;
while (!StackEmpty(stack))
{
GetTop(stack, p);
if (p->rchild == r)
{
cout << p->data;
Pop(stack, p);
r = p;
}
else
{
p = p->rchild;
flag = false;
}
}
} while (!StackEmpty(stack));
cout << endl;
DestoyStack(stack);
}
层次遍历
前置队列代码
typedef struct
{
BTNode* data[MAXSIZE];
int front, rear;
}SqQueue;
void InitQueue(SqQueue*& q)
{
q = (SqQueue*)malloc(sizeof(SqQueue));
q->front = q->rear = -1;
}
bool enQueue(SqQueue*& q, BTNode* e)
{
if (q->rear == MAXSIZE - 1)
return false;
q->rear++;
q->data[q->rear] = e;
//q->data[++q->rear]=e;
return true;
}
bool deQueue(SqQueue*& q, BTNode*& e)
{
if (q->front == q->rear)
return false;
q->front++;
e = q->data[q->front];
return true;
}
bool QueueEmpty(SqQueue* q)
{
return (q->front == q->rear);
}
void LevelOrder(BTNode* b)
{
BTNode* p;
SqQueue* queue;
InitQueue(queue);
enQueue(queue, b);
while (!QueueEmpty(queue))
{
deQueue(queue, p);
cout << p->data;
if (p->lchild != NULL)
enQueue(queue, p->lchild);
if (p->rchild != NULL)
enQueue(queue, p->rchild);
}
}