树形结构的查找(二叉排序树-创建、查找、插入、删除)

本文深入探讨了二叉排序树的基本概念,包括如何创建、查找、插入和删除节点。通过对二叉排序树的操作,理解其在数据组织和检索中的效率优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、二叉排序树

1、定义:对于根节点,若左子树不空,则左子树上所有节点值小于根节点,若右子树不空,则右子树所有节点值大于等于根节点,左右子树也是二叉排序树。
2、构造:按关键字读入次序构造。第一个关键字作为根节点,然后每读入一个关键字,就与根节点比较,若较小,则当左子树为空时,把它作为根的左孩子,若左子树非空,则把它插入根的左子树上;若较大,则当右子树为空时,把它作为根的右孩子,若右子树非空,则把它插入根的右子树上。
3、二叉排序树建立、插入、删除、查找、前序遍历、中序遍历:
#include <iostream>
#include <vector>
using namespace std;

struct BiNode
{//二叉排序树节点的数据类型
    int key;
    BiNode *lchild,*rchild;
};
class BiSortTree{
    public:
        BiSortTree(int a[],int n);//构造函数
        BiNode *Getroot();//获取指向根节点的指针
        void pre_order(BiNode *root);//前序遍历二叉树
        void mid_order(BiNode *root);//中序遍历二叉树
        BiNode *CreatBiSortTree(int a[],int n);//建立二叉排序树
        BiSortTree(){};//构造函数
        BiNode *InsertBST(BiNode *root,BiNode *s);//非递归插入节点s
        BiNode *InsertBST1(BiNode *root,BiNode *s);//递归插入节点s
        void DeleteBST(BiNode *p,BiNode *f);//删除节点p,f是p的双亲节点
        void NextRep(BiNode *p);//删除节点p,查找中序序列中p的后继s代替p
        BiNode *SearchBST(BiNode *root,int k);//查找,非递归
        BiNode *SearchBST1(BiNode *root,int k);//查找,递归
    private:
        BiNode *root;
};
BiSortTree::BiSortTree(int a[],int n)//构造函数
{
    BiNode *root=NULL;
    for(int i=0;i<n;i++)
    {
        BiNode *s=new BiNode;
        s->key=a[i];
        s->lchild=NULL;
        s->rchild=NULL;
        root=InsertBST1(root,s);
    }
}
//前序遍历二叉树
void BiSortTree::pre_order(BiNode *root)
{
    if(root!=NULL)
    {
        cout<<root->key<<"  ";
        pre_order(root->lchild);
        pre_order(root->rchild);
    }
}
void BiSortTree::mid_order(BiNode *root)//中序遍历二叉树
{
    if(root)
    {
        mid_order(root->lchild);
        cout<<root->key<<"  ";
        mid_order(root->rchild);
    }
}
//二叉排序树上插入一个关键字(非递归)
BiNode *BiSortTree::InsertBST(BiNode *root,BiNode *s)
{//在根为root的树上插入节点s,若树空则插入s为根节点,否则,根据值的大小选择插入左子树还是右子树
    BiNode *p,*q;
    if(!root) return s;
    else
    {
        q=NULL;p=root;
        while(p)
        {
            q=p;//q为p的根
            if(s->key<p->key) p=p->lchild;
            else p=p->rchild;
        }//s插入节点q的左孩子或右孩子
        if(s->key
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值