Chinaunix首页 | 论坛 | 博客
  • 博客访问: 342626
  • 博文数量: 72
  • 博客积分: 2130
  • 博客等级: 大尉
  • 技术积分: 857
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-05 16:10
文章分类

全部博文(72)

文章存档

2010年(5)

2009年(14)

2008年(53)

分类: C/C++

2008-10-10 11:19:05

#include
#include
#include

#define MAXSIZE 100

typedef struct BiTNode
{
        int data;
        struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

typedef BiTree DataType;

typedef struct stack
{
        DataType data[MAXSIZE];
        int top;
}Stack;

void StackInit(Stack *S)
{
        S->top=-1;
}

int StackEmpty(Stack *S)
{
        return S->top==-1;
}

int StackFull(Stack *S)
{
        return S->top==MAXSIZE-1;
}

void push(Stack *S, DataType value)
{
        if(StackFull(S))
        {
                printf("Stack is full!\n");
                exit(-1);
        }
        S->data[++S->top]=value;
}

void pop(Stack *S)
{
        if(StackEmpty(S))
        {
                printf("Stack is empty!\n");
                exit(-1);
        }
        S->top--;
}

DataType top(Stack *S)
{
        if(StackEmpty(S))
        {
                printf("Stack is empty!\n");
                exit(-1);
        }
        return S->data[S->top];
}

void CreateBiTree(BiTree *T)
{
        int ch;
        scanf("%d",&ch);
        if(ch==-1)
        {
                *T=NULL;
        }
        else
        {
                *T=(BiTree)malloc(sizeof(BiTNode));
                if(!(*T))
                        printf("memory alloc error");
                (*T)->data=ch;
                CreateBiTree(&((*T)->lchild));
                CreateBiTree(&((*T)->rchild));
        }
}


void PreOrderTraverse(BiTree T)
{
        BiTree p=T;
        Stack *s;
        StackInit(s);

        while(p!=NULL||!StackEmpty(s))
        {
                while(p!=NULL)
                {
                        printf("%3d",p->data);
                        push(s,p);
                        p=p->lchild;
                }
                if(!StackEmpty(s))
                {
                        p=top(s);
                        pop(s);
                        p=p->rchild;
                }
        }


void InOrderTraverse(BiTree T)
{
        BiTree p=T;
        Stack *s;
        StackInit(s);

        while(p!=NULL||!StackEmpty(s))
        {
                while(p!=NULL)
                {
                        push(s,p);
                        p=p->lchild;
                }
                if(!StackEmpty(s))
                {
                        p=top(s);
                        pop(s);
                        printf("%3d",p->data);
                        p=p->rchild;
                }
        }
}

int main(void)
{
        BiTree T;
        printf("请输入创建一棵二叉树的先序序列:\n");
        CreateBiTree(&T);
        printf("先序序列为:");
        PreOrderTraverse(T);
        printf("\n");
        printf("中序序列为:");
        InOrderTraverse(T);
        printf("\n");
      
        return 0;
}




阅读(910) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~