构建简单的二叉树(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编译通过...

posted on 2012-02-20 14:17  Mayvar  阅读(402)  评论(0编辑  收藏  举报

导航