简单二叉数的c程序编写

一剑行天下 posted @ 2008年11月20日 01:07 in 二叉数 , 1529 阅读

#include<stdio.h>
#include<stdlib.h>
//#include "molloc.h"
 struct btreenode           //创建结构体
{
        char data;
        struct btreenode *lchild,*rchild;
};

int isalphabet(char i)//判断是否是字符
{
        if (i >= 'a' && i <='z' || i >= 'A' && i <='Z' || i=='@')
                return 1;
        else return 0;
}

struct btreenode *creat(void)//创建结点
{
        struct btreenode *p;
        p=(struct btreenode *)malloc(sizeof(struct btreenode));
        char i;
        printf("Please input a char:\t");
        fflush(stdin);
        char c='3';
        scanf("%c",&i);
        c=getchar();
        //printf ("%d\n", i>='a');// 验证了字符是否输入正确
        //fflush(stdin);
        while(!isalphabet(i))
        {
                //printf("%d\n",isalphabet(i));
                printf("Sorry, your input char is not in alphabet, please input again:");
                scanf("%c",&i);
                fflush(stdin);//将缓存清空,以防回车键被i接受,
        }
        if(i=='@') p= NULL;
        else
        {
                p = (struct btreenode*)malloc(sizeof(struct btreenode));
                if(p == NULL)
                {
                        printf("Out of space!\n");
                        return p ;
                }
                p->data=i;
                p->lchild=creat();
                p->rchild=creat();
        }
        return p;

}

struct btreenode *creat_boot(void)//创建树根
{
        struct btreenode *treeboot;
        treeboot=(struct btreenode*)malloc(sizeof(struct btreenode));
        treeboot=creat();
        return(treeboot);

}
void outputTree(struct btreenode *pbnode)//后续输出
{
        int i;
        if(pbnode!=NULL)
        {
                outputTree(pbnode->lchild);
                outputTree(pbnode->rchild);
                printf("%c\n",pbnode->data);
        }
}
 void preorder(struct btreenode *pbnode)
        {
                if(pbnode==NULL) return ;
                printf("%c\t",pbnode->data);
                preorder(pbnode->lchild);
                preorder(pbnode->rchild);
        }
        main()
        {
                struct btreenode *tree;
                int i;
                printf("input number creat tree\n");
                tree=creat_boot();
                outputTree(tree);
                preorder(tree);

        }
//程序运行
/*input number creat tree
Please input a char:    a
1
Please input a char:    b
1
Please input a char:    c
1
Please input a char:    d
1
Please input a char:    @
0
Please input a char:    @
0
Please input a char:    @
0
Please input a char:    @
0
Please input a char:    @
0
d
c
b
a



a       b      c     d
  3. 创建一棵二叉树
  首先我们定义一个DataType类型的变量i,用于存放我们输入的字符(即作为缓冲区),并用scanf函数去接收它,由于使用scanf函数时,会出现吸收我们输入的回车字符,并将会车作为接收的字符的情况发生,为了避免这种情况,我们用函数fflush(stdin)将缓冲区的字符全部冲掉,然后再吸收我们输入的字符,就可以完全避免此类问题的发生。
  我们定义我们输入的字符是从a-z或者是A-Z,用字符@为我们结束当前结点左或者右结点的字符,然后递归调用左右子树,此时我们将一棵二叉树全整的创建出来了。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter