二叉排序树(BST)插入

先用search找到所应该要插入的位置(假定没有重复的点)

之后找到对应位置,左孩子或者右孩子为空的点将其插入,所以插入的节点必然是树的叶子

在构建BST时用到了插入的操作

代码如下

#include<iostream>
#include<cstdlib>
using namespace std;
#define len 15

typedef struct Bitnode
{
    int data;
    struct Bitnode *lc;
    struct Bitnode *rc;
}Bitnode,*Bitree;

void searchBiTreeNode(Bitree &root,Bitree &node) // 查找
{
    if(root==NULL)
        return ;
    if(root->data>node->data){
        searchBiTreeNode(root->lc,node);
        if(root->lc==NULL)
            root->lc=node;
    }
    else if(root->data<node->data){
        searchBiTreeNode(root->rc,node);
        if(root->rc==NULL){
            root->rc=node;
        }
    }
}

void insertNode(Bitree &bitree,Bitree &node) // 插入
{
    if(bitree==NULL)
        bitree=node;
    else
        searchBiTreeNode(bitree,node);
}

void createbst(Bitree &bitree,int arr[]) // 创建BST树
{
    for(int i=0;i<len;i++){
        Bitree s=(Bitree)malloc(sizeof(Bitnode));
        s->data=arr[i];
        s->lc=NULL;
        s->rc=NULL;
        insertNode(bitree,s);
    }
}

void midsearchbitreeprint(Bitree &bitree) // 中序遍历输出
{
    if(bitree==NULL)
        return ;
    midsearchbitreeprint(bitree->lc);
    printf("%d ",bitree->data);
    midsearchbitreeprint(bitree->rc);
}

Bitree BST_Search(Bitree &root,int x){ // 查找
    if(root == NULL){
        return NULL;
    }else if(root->data>x){
        return BST_Search(root->lc,x);
    }else if(root->data<x){
        return BST_Search(root->rc,x);
    }else{
        return root;
    }
}

int main()
{
    int arr[len]={62,88,58,47,35,73,51,99,37,93,23,27,45,21,12};
    Bitree bitree=NULL;
    createbst(bitree,arr);
    midsearchbitreeprint(bitree);
    printf("\n");
    Bitree searchNode = BST_Search(bitree,27);
    if(searchNode == NULL){
        printf("没有找到此节点\n");
    }else{
        if(searchNode->lc==NULL && searchNode->rc==NULL){ //叶子节点
            printf("所查找的节点x=%d是叶子节点\n",searchNode->data);
        }else{
            if(searchNode->lc != NULL){
                printf("x=%d所在节点的左孩子: %d\n",searchNode->data,searchNode->lc->data);
            }
            if(searchNode->rc != NULL){
                printf("x=%d所在节点的右孩子: %d\n",searchNode->data,searchNode->rc->data);
            }
        }
    }
    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值