二叉树的遍历

来源:互联网 发布:python d3.js 编辑:程序博客网 时间:2024/04/25 22:19
 

#include<stdio.h>
#include<stdlib.h>
int count;
struct tree
{
 struct tree *l;
 struct tree *r;
 char data;
};

tree *build()
{
 tree *root;
 char ch;
 scanf("%c",&ch);
 if(ch=='.')
  root=NULL;
 else
 {
  root=(tree*)malloc(sizeof(tree));
  root->data=ch;
  root->l=build();
  root->r=build();
 }
 return root;
}

void pre(tree *root)
{
 if(root)
 {
  printf("%c",root->data);
  pre(root->l);
  pre(root->r);
 }
}

void in(tree *root)
{
 if(root)
 {
  in(root->l);
  printf("%c",root->data);
  in(root->r);
 }
}

void later(tree *root)
{
 if(root)
 {
  later(root->l);
  later(root->r);
  printf("%c",root->data);
 }
}

void sum(tree *root)
{
 if(root==NULL)
  return;
 if(root->l==NULL&&root->r==NULL)
  count++;
 sum(root->l);
 sum(root->r);
}


int main()
{
 tree *root=NULL;
 char a;
 do
 { 
  count=0;
  printf("创建二叉树表请按1\n");
  printf("先序输出请按2\n");    
  printf("中序输出请按3\n");
  printf("后序输出请按4\n");
  printf("统计叶子结点数请按5\n");
  printf("退出请按0\n");
  scanf("%d",&a);
  switch(a)
  {
  case 1:root=build();break;
  case 2:pre(root);break;
  case 3:in(root);break;
  case 4:later(root);break;
  case 5:{

sum(root);

printf("%d",count);

break;

}
  case 0:exit(0);
  }
  getchar();
  printf("\n");
 }while(a!=0);
 return 0;
}

/*
输入:AB..CD..E...
中序遍历: B A D C E
*/

原创粉丝点击