二叉树的创建、先序、中序、后序遍历

来源:互联网 发布:电气火灾监控软件 编辑:程序博客网 时间:2024/05/29 04:41
#include <stdio.h>
#include <stdlib.h>


#define ERROR 0
#define OK 1


typedef struct bitree
{
    int data;
    struct bitree *lchild;
    struct bitree *rchild;
}bitree_s,*pbitree;


//以先序方式,创建一颗二叉树;
int creat_tree(pbitree *T,int j,int* i)
{
    (*T) = (bitree_s *)malloc(sizeof(bitree_s));
    if(!(*T)) return ERROR;
    (*T)->data = (*i);
    printf("%d\n",((*T)->data));
    (*T)->lchild = NULL;
    (*T)->rchild = NULL;
    (*i) += 1;
    j -= 1;
    if(j==0)
    {
        return OK;
    }
    creat_tree(&((*T)->lchild),j,i);
    creat_tree(&((*T)->rchild),j,i);
}
//以先序进行遍历
int preorder(pbitree T)
{
    if(!T) return ERROR;
    printf("%d\n",T->data);
    preorder(T->lchild);
    preorder(T->rchild);
}
//以中序进行遍历
int minorder(pbitree T)
{
    if(!T) return ERROR;
    minorder(T->lchild);
    printf("%d\n",T->data);
    minorder(T->rchild);


}
//以后序进行遍历
int lastorder(pbitree T)
{
    if(!T) return ERROR;
    lastorder(T->rchild);
    printf("%d\n",T->data);
    lastorder(T->lchild);


}


int main()
{
    int count = 1;
    int deep = 3;
    pbitree tree;
    printf("hello world\n");
    creat_tree(&tree,deep,&count);
    printf("pre order transvers\n");
    preorder(tree);
    printf("min order transvers\n");
    minorder(tree);
    printf("last order transvers\n");
    lastorder(tree);
}
阅读全文
0 0