数据结构实验之二叉树的建立与遍历

来源:互联网 发布:体脂秤什么牌子好 知乎 编辑:程序博客网 时间:2024/06/11 17:47

这道题它把空格的情况用‘ ,’来进行表示所以相对比较简单了……

对这题进行分析,先根据先序的顺序建立二叉树,再通过调用几个功能不同的函数进行不同效果的操作。

#include<stdio.h>  #include<stdlib.h>  #include<string.h>  int sum=0;  typedef struct node  //通过typedef自定义类型可以简化书写;{      char data;      struct node*lc,*rc;  //定义一个左边的一个右边的结构体指针,(链表);}tree,*tree1;  tree1 build(tree1 t)  //二叉树构建函数;{      char c;      c = getchar();  //一个一个的输入字符,再经行筛选;    if(c==',')      {          t = NULL;  //','代表空;    }      else      {          t = (tree1)malloc(sizeof(tree));//为t开辟空间,将当下的字符储存起来;          t->data = c;          t->lc = build(t->lc);  //递归调用根的左边;        t->rc = build(t->rc);  //递归调用根的右边;    }      return t;  //整体就是通过链表将二叉树建立起来,二叉树的建立通过递归调用分成左右两部分进行建立;}  void zx(tree1 t)  //进行中序遍历;{      if(t!=NULL)      {          zx(t->lc); //根据二叉树的定义,如果左边不为空就输出;         printf("%c",t->data);          zx(t->rc);  //调用完左边之后在进行右边的调用;    }  //注意这里在遍历的过程中,每个根始终是左右两边独立进行的;}  void hx(tree1 t)  //后序遍历;{      if(t != NULL)  //通过这个条件可以找到递归的最小的根;    {          hx(t->lc);  //根据后序遍历的要求调用的左边最后不再有分支了;        hx(t->rc);  //根据后序遍历的要求调用的右边最后不再有分支了;        printf("%c",t->data);      }  }  void leaf(tree1 t)  //查找叶子的个数;{      if(t != NULL)      {          if(t->lc == NULL && t->rc == NULL)//根据叶子的定义左右应该都没有子树杈;          {              sum++;          }          else  //否则调用左右子叉;        {              leaf(t->lc);              leaf(t->rc);          }      }  }  int deep (tree1 t)  //求深度;    {          if(t!=NULL)          {              int a = deep(t->lc),b = deep(t->rc);              if(a > b)  //判断他们的子叉是否为空,但是由于左右子叉可能就一个为空,所以要求得最大深度;            {                  return a+1;              }              else              {                  return b+1;              }          }          else          {              return 0;          }          return 0;      }  int main()  {      tree1 tree2=NULL;//重新开辟一个结构体,用来放排好的二叉树;      tree2=build(tree2);      zx(tree2);      printf("\n");      hx(tree2);    printf("\n");      leaf(tree2);      printf("%d\n%d\n",sum,deep(tree2));      return 0;  }  
连接 http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2136&cid=1145

原创粉丝点击