参考:http://blog.csdn.net/zdcsky123/article/details/6668922
#include <stdio.h>
#include <stdlib.h>
#define N 64
typedef struct node
{
int no;
struct node *lchild, *rchild;
} BiNode,*Bitree;
typedef struct
{
Bitree data[N];
int top;
} sqstack;
typedef struct
{
Bitree data[N];
int front, rear;
} sequeue;
/******************** stack operation *******************************/
sqstack *CreateEmptyStack()
{
sqstack *s;
s = (sqstack *)malloc(sizeof(sqstack));
s->top = -1;
return s;
}
int EmptyStack(sqstack *s)
{
return (-1 == s->top);
}
int FullStack(sqstack *s)
{
return (N-1 == s->top);
}
void PushStack(sqstack *s, Bitree x)
{
s->data[++s->top] = x;
return;
}
Bitree PopStack(sqstack *s)
{
return s->data[s->top--];
}
Bitree GetTop(sqstack *s)
{
return s->data[s->top];
}
/********************** queue operation ********************************/
sequeue *CreateEmptyQueue()
{
sequeue *sq;
sq = (sequeue *)malloc(sizeof(sequeue));
sq->front = sq->rear = 0;
return sq;
}
int EmptyQueue(sequeue *sq)
{
return (sq->front == sq->rear);
}
void EnQueue(sequeue *sq, Bitree x)
{
sq->rear = (sq->rear + 1) % N;
sq->data[sq->rear] = x;
return;
}
Bitree DeQueue(sequeue *sq)
{
sq->front = (sq->front + 1) % N;
return sq->data[sq->front];
}
/*********************************************************************/
//递归构造二叉树
Bitree CreateBitree(int i, int n)
{
Bitree root;
root = (Bitree)malloc(sizeof(BiNode));
root->no = i;
if (2*i <= n) root->lchild = CreateBitree(2*i, n);
else root->lchild = NULL;
if (2*i+1 <= n) root->rchild = CreateBitree(2*i+1, n);
else root->rchild = NULL;
return root;
}
//递归先序遍历二叉树
void PreOrder(Bitree root)
{
if (root == NULL) return;
printf("%d ", root->no);
PreOrder(root->lchild);
PreOrder(root->rchild);
return;
}
//栈实现非递归的先序遍历
void PreOrder_1(Bitree root) // non-recursive
{
sqstack *s;
s = CreateEmptyStack();
PushStack(s, root);
while ( ! EmptyStack(s) )
{
root = PopStack(s);
printf("%d ", root->no);
if (root->rchild) PushStack(s, root->rchild);
if (root->lchild) PushStack(s, root->lchild);
}
return ;
}
void InOrder(Bitree root)
{
if (root == NULL) return;
InOrder(root->lchild);
printf("%d ", root->no);
InOrder(root->rchild);
return;
}
void PostOrder(Bitree root)
{
if (root == NULL) return;
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%d ", root->no);
return;
}
//队列实现层序遍历
void NoOrder(Bitree root)
{
sequeue *sq;
sq = CreateEmptyQueue();
EnQueue(sq, root);
while ( ! EmptyQueue(sq) )
{
root = DeQueue(sq);
printf("%d ", root->no);
if (root->lchild) EnQueue(sq, root->lchild);
if (root->rchild) EnQueue(sq, root->rchild);
}
printf("\n");
return;
}
int main()
{
Bitree root;
root = CreateBitree(1, 10);
printf("PreOrder : ");
PreOrder(root);
printf("\n");
printf("InOrder : ");
InOrder(root);
printf("\n");
printf("PostOrder : ");
PostOrder(root);
printf("\n");
printf("NoOrder : ");
NoOrder(root);
return 0;
}