二叉树的链式存储

/*win-tc*/
#include"stdio.h"
#include"stdlib.h"
#include"conio.h"
#include"ctype.h"
#define MAXSIZE 100
#define NULL 0

typedef struct tree     /*定义树结点结构*/
{
    struct tree* lchild;
    struct tree* rchild;
    int data;
}treenode,*bintree;

bintree insert_node(bintree root,int node) /*向二叉树中插入新结点*/
{
    bintree newnode;
    bintree currentnode;
    bintree parentnode;
    newnode=(bintree)malloc(sizeof(treenode));
    newnode->data=node;
    newnode->rchild=NULL;
    newnode->lchild=NULL;
    if(root==NULL)         /*空树,新结点成为根结点*/
        return newnode;
    else                  /*插入孩子结点*/
    {
        currentnode=root;
        while(currentnode!=NULL)
        {
            parentnode=currentnode;     /*判断插入数据与当前结点的大小*/
            if(currentnode->data>node)  /*如果数据小则将光标移到结点的左指针*/
                currentnode=currentnode->lchild;
            else                        /*如果数据大则将光标移到结点的右指针*/
                currentnode=currentnode->rchild;
        }
        if(parentnode->data>node)      /*插入数据小则做为左孩子*/
            parentnode->lchild=newnode;
        else                           /*插入数据大则做为右孩子*/
            parentnode->rchild=newnode;
    }
    return root;
}

bintree create_tree(int data[],int len)  /*利用插入算法创建二叉树*/
{
    bintree root;
    int i;
    root=NULL;
    for(i=0;i<len;i++)
        root=insert_node(root,data[i]) ;
    return root;
}

void preorder(bintree root)    /*先序遍历二叉树的递归算法*/
{
    if(root!=NULL)
    {
        printf("%d  ",root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
}

void inorder(bintree root)    /*中序遍历二叉树的递归算法*/
{
    if(root!=NULL)
    {
        preorder(root->lchild);
        printf("%d  ",root->data);
        preorder(root->rchild);
    }
}

void postorder(bintree root)   /*后序遍历二叉树的递归算法*/
{
    if(root!=NULL)
    {
        preorder(root->lchild);
        preorder(root->rchild);
        printf("%d  ",root->data);
    }
}

void main()
{
    bintree root=NULL;
    int i,index;
    int value;
    int nodelist[MAXSIZE];
    clrscr();
    printf("please input the elenents of binary tree(Exit for 0):/n/n");
    index=0;
    scanf("%d",&value);
    while(value!=0)           /*输入结点*/
    {
        nodelist[index]=value;
        index++;
        scanf("%d",&value);
    }
    root=create_tree(nodelist,index);
    printf("/n/nthe preorder reaversal result is: [ ");
    preorder(root);
    printf("]/n/n");
    printf("/n/nthe inorder reaversal result is: [ ");
    inorder(root);
    printf("]/n/n");
    printf("/n/nthe postorder reaversal result is: [ ");
    postorder(root);
    printf("]/n/n");
    getch();
}
结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值