华清远见C语言学习笔记九

/*
 * test.c
 *
 *  Created on: Jul 5, 2012
 *      Author: 孙旭
 *      华请远见嵌入式实验室
 */
/*有序二叉树*/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

/*定义一个结构体*/
typedef struct student{
 int grade;
 struct student *lchild;
 struct student *rchild;
}std;

/*创建一个有序的二叉树并以0作为结束符*/
std *create_student()
{
 printf("please enter grade\n");
 std *head,*root,*new_node;
 root=(std *)malloc(sizeof(std));
 scanf("%d",&root->grade);
 head=root;
 while(1)
 {

  new_node=(std *)malloc(sizeof(std));
  if(new_node==NULL)
  {
   printf("create new node error");
   exit(0);
  }
  scanf("%d",&new_node->grade);
  if(new_node->grade==0)
   break;
  else
  {
   if((root->lchild==NULL)&&(root->grade>new_node->grade))
   {
    root->lchild=new_node;
    new_node->lchild=NULL;
    new_node->rchild=NULL;
   }
   else if((root->rchild==NULL)&&(root->grade<=new_node->grade))
   {
    root->rchild=new_node;
    new_node->rchild=NULL;
    new_node->lchild=NULL;
   }
   else if((root->rchild!=NULL)||(root->rchild!=NULL))
   {
    while(root->lchild!=NULL||root->rchild!=NULL)
    {
     if((new_node->grade<root->grade)&&(root->lchild!=NULL))
     root=root->lchild;
     else if((new_node->grade>=root->grade)&&(root->rchild!=NULL))
     root=root->rchild;
    }
    if(new_node->grade<root->grade)
     root->lchild=new_node;
    else if(new_node->grade>=root->grade)
    {
     root->rchild=new_node;
    }
    new_node->lchild=NULL;
    new_node->rchild=NULL;
    root=head;
   }
  }
 }
 printf("-----创建二叉树完成-----\n");
 return head;
}

/*从二叉树中搜寻节点*/
void search_student(std *head)
{
 printf("请输入查找的节点:\n");
 int node;
 scanf("%d",&node);
 while(1)
 {
  if((head->grade>node)&&(head->lchild!=NULL))
  {
   head=head->lchild;
  }

  else if((head->grade<node)&&(head->rchild!=NULL))
  {
   head=head->rchild;
  }
  else{
   printf("==节点查找成功==\n");
    printf("%d\n",head->grade);
    break;
      }
 }
}

/*翩历二叉树*/
void print_student(std *head)
{
 if(head)
 {
  print_student(head->lchild);
  printf("%d\t",head->grade);
  print_student(head->rchild);
 }
}

/*主函数*/
int main()
{
 std *head;
 head=create_student();
 print_student(head);
 printf("\n");
 search_student(head);
 return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值