/*
* 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;
}