二叉树的遍历

 

#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
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值