构建简单的二叉树(C)

#include "stdafx.h"

#include "stdlib.h"
#include "stdio.h"

struct  tree{
char info;
struct tree *left;
struct tree *right;}
;

struct tree*root;

void print_tree(struct tree *r,int l);

struct tree *stree(struct tree *root,struct tree *r,char info)
{
 if(!r)
 {
  r=(struct tree*)malloc(sizeof(struct tree));
  if(!r)
  {
   printf("Out of Mem");
   exit(0);
  }

  r->left = NULL;
  r->right= NULL;
  r->info = info;

  if(! root)return r;
  if(info<root->info)
   root->left = r;
  else
   root->right= r;
  return r;
 }
 if(info<r->info)
  stree(r,r->left ,info);
 else
  stree(r,r->right ,info);

 return root;
}

 

int main(void)
{
 char s[80];
 root = NULL;
 do
 {
  printf("Enter a letter:\n");
  gets(s);
  root = stree(root,root,*s);
 }
 while(*s);

 print_tree(root,0);

 return 0;
}

void print_tree(struct tree *r,int l)
{
 int i;
 if(!r)return;
 print_tree(r->right,l+1);
 for(i=0;i<1;++i)printf("  ");
 printf("%c\n",r->info);
 print_tree(r->left ,l+1);
}

VC6.0编译通过...

转载于:https://www.cnblogs.com/Mayvar/archive/2012/02/20/wanghonghua_201202200209.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值