创建二叉排序树并查找值为x的节点(c语言版)

#include<stdio.h>
#include<stdlib.h>
/*所谓二叉排序树,即左子树的值小于根节点,右子树的值大于根节点;中序遍历的结果从左到右为升序*/
typedef struct node
{   int data;
    struct node *lchild;
    struct node *rchild;
}node;


/*查找x*/
/*算法思想:
    查找x的结果有两种,找到和找不到,找不到又包括空树和树中不包括该节点,找到返回1,否则返回0
*/
int search(node *root,int x)
{   node *p;
    if(root!=NULL)
    {   p=root;
        while(p!=NULL){         /*找到返回1*/
            if(p->data==x) return 1;
            if(x>p->data) p=p->rchild;
            else p=p->lchild;
        }
    }
    return 0;                   /*是空树或者没找到时返回0*/
}


 /*二叉排序树的插入*/
int insert(node **root,int x)       /*双指针*/
{
    node *current,*parent=NULL,*s;
    current=*root;


    while(current!=NULL)            /*当不是空树时,查找x应该插入的位置*/
    {
        if(current->data==x) return 0;
        parent=current;             /*parent记录x应该插入的位置的根节点*/
        if(current->data<x) current=current->rchild;
        else current=current->lchild;
    }


    s=(node*)malloc(sizeof(node));  /*把s放在while循环后面,当有重复数据时,可以少创建一个节点*/
    s->data=x;s->lchild=NULL;s->rchild=NULL;


    if(parent==NULL) *root=s;
    else if(x<parent->data) parent->lchild=s;
    else parent->rchild=s;
    return 1;
}


/*二叉排序树的遍历*/
void travel(node *root)
{
    if(root==NULL) return;
    if(root->lchild!=NULL) travel(root->lchild);
    printf("%d ",root->data);
    if(root->rchild!=NULL) travel(root->rchild);
}


int main()
{
    int a[8],i=0,k,n,x;
    printf("\ninput numbers end by -1:\n");
    scanf("%d",&n);
    while(n != -1){ a[i]=n;i++;scanf("%d",&n);} k=i; /*将用户输入的数据存到a[]数组*/


    node *root=NULL;                                /*为什么用双指针*/
    for(k=0; k<i; k++)
    { insert(&root,a[k]);}                          /*用插入的方法创建二叉有序树*/


    printf("\n中序遍历:\n\n");                     /*中序遍历输出*/
    travel(root);


    printf("\n\n请输入需要查找的x:\n\n");          /*查找输入的数据*/
    scanf("%d",&x);


    int s=search(root,x);
    if(s==1)
    {
        printf("\n数据%d存在\n",x);
    }
    else printf("\n数据%d不存在\n",x);
    return 0;

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值