Home Database Mysql Tutorial 16.二叉排序树

16.二叉排序树

Jun 07, 2016 pm 04:13 PM
sort data Find Linear

一、二叉排序树 如果要查找的数据集是有序线性表且是顺序存储的,查找可以用折半、插值、斐波那契等查找算法来实现。然后,由于有序,当我们在插入和删除操作上,就需要耗费大量的时间。下面将要学习的二叉排序树,就是一种既可以使得插入和删除效率不错,又

一、二叉排序树 如果要查找的数据集是有序线性表且是顺序存储的,查找可以用折半、插值、斐波那契等查找算法来实现。然后,由于有序,当我们在插入和删除操作上,就需要耗费大量的时间。下面将要学习的二叉排序树,就是一种既可以使得插入和删除效率不错,又可以比较高效率地实现查找的算法。为此,构造一棵二叉排序树的目的并不是为了排序,而是为了提供查找和插入删除关键字的速度。 1.二叉排序树概念 二叉排序树(Binary Sort Tree),又称为二叉查找树,或者是一棵空树,或者是具有下列性质的二叉树。 ◆若它的左子树不空,则左子树上所有结点的值均小于它的根结构(双亲结点)的值; ◆若它的右子树不空,则右子树上所有结点的值均大于它的根结点(双亲结点)的值; ◆它的左、右子树也分别为二叉排序树。 2.二叉树结点结构
/*二叉树的二叉链表结点结构定义*/
typedef struct BiTNode                        //结点结构
{
    int data;                                            //结点数据
    Struct BiTNode *lchild,*rchild;       //左右孩子指针
}BiTNode,*BiTree;   
Copy after login
二、二叉排序树操作算法 1.二叉排序树的查询操作
/*递归查找二叉排序树T中是否存在key,
   * 指针f指向T的双亲,其初始调用值为NULL
    *若查找成功,则指针p指向该数据元素结点,并返回TRUE;否则指针p指向查找路径上访问的最后一个结点并返回FALSE*/
Status SearchBST(BiTree T,int key,BiTree f,BiTree *p)
{
    if(!T)                            //查找不成功(为空树)
    {
            *p=f;
            return FALSE;
    }
    else if(key==T->data)  //查找成功
    {
            *p=T;
            return TRUE;
    }
    else if(key<T->data)
            return SearchBST(T->lchild,key,T,p);        //在左子树继续查找
    else
            return SearchBST(T->rchild,key,T,p);        //在右子树继续查找  
}
Copy after login
实例: 假如有一数据集合={62,88,58,47,35,73,51,99,37,93},查找的关键字key=93。 使用二叉排序树查找算法步骤如下: ①根据二叉排序树定义将该数据集合构造成一棵二叉排序树(中序遍历); \
②调用二叉排序树查询算法SearchBST(T,93,NULL,P)查询关键字,其中,SearchBST函数是一个可递归运行的函数,参数T是一个二叉树链表、key代表要查询的关键字、二叉树f指向T的双亲。当T指向根结点时,f的初值就为NULL,它在递归时有用,最后的参数p是为了查找成功后可以得到查找到的结点位置。 ③ if(!T){ .... }语句。用来判断当前二叉树是否到叶子结点,此时当前T指向根结点62的位置,由于T不为空,故该语句片段不执行。 ④esle if(key==T->data)语句。即查找到相匹配的关键字执行语句,显然93!=62,故该语句片段不执行。 ⑤else if(keydata)语句。即当要查找关键字小于当前结点时执行语句,由于93>62,故该语句片段不执行。 ⑥else{....}语句。即当即当要查找关键字大于当前结点时执行语句,93>62,所以以递归调用SearchBST(T->rchild,key,T,p)。此时,T指向了62的右孩子88,f指向88的双亲结点,即62。如图: \
⑦此时第二层SearchBST,因93比88大,所以执行else{....}语句,再次递归调用SearchBST(T->rchild,key,T,p)。此时T指向了88的右孩子99。 \
\ ⑧此时第三层SearchBST,因93比99小,所以执行else if(keydata)语句,再次递归调用SearchBST(T->lchild,key,T,p)。此时T指向了99的左孩子93。 \
⑨第四层SearchBST,因key等于T->data,所以执行第10~11行,此时指针p指向93所在的结点并返回True到第三层、第二层、第一层,最终返回函数True。 2.二叉排序树的插入操作 所谓二叉排序树的插入,即将关键字放到树中的合适位置。 (1)二叉排序树的插入算法
/*当二叉排序树T中不存在关键字等于key的数据元素时,
 *    插入key并返回TRUE,否则返回FALSE*/
Status InsertBST(BiTree *T,int key)
{
    BiTree p,s;
    /*调用查找函数查找是否存在该关键字*/
    //a.若查找不成功
    if(!SearchBST(*T,key,NULL,&p))    
    {
          s=(BiTree)malloc(sizeof(BiTNode));    //为结点s开辟一段内存空间
          s->data=key;                                       //将关键字存放到s指向结点的数据域中
          s->lchid=s->rchild=NULL;                //初始化结点s的左右指针域
         if(!p)
                *T=s;                //插入s为新的根结点
         else if(key<p->data)//若关键字小于p结点数据值,插入s为结点p的左孩子
                p->lchild = s;   
          else                        //若关键字大于p结点数据值,插入s为结点p的右孩子
                p->rchild=s;   
    }
    /*树中已有关键字相同的结点,不再插入*/
    else
    {
            return FALSE;    
    }
}
Copy after login
举例:假如我们调用函数是"InsertBST(T,93);",那么结果就是FALSE;假如调用函数为"InsertBST(T,95);",那么一定是就是在93的结点增加一个右孩子95,并返回TRUE。需要注意的是,由于插入算法事先调用了SearchBST(*T,key,NULL,&p)查找算法且使用中序遍历二叉树,最终我们可知指针p指向的结点为93. 3.构建二叉排序树算法
/*假如有一个数据集={62,88,58,47,35,73,51,99,37,93}
    * 构建一个二叉排序树*/
int i;
int a[0]={62,88,58,47,35,73,51,99,37,93};
BiTree T=NULL;
for(i=0;i<10;i++)
{
    InsertBST(&T,a[i]);
}
Copy after login
4.二叉排序树删除操作算法 \
(1)采用递归方式对二叉排序树T查找key,找到后调用Delete函数删除该结点 /*若二叉排序树T中存在关键字等于key的数据元素时,则删除该数据元素结点 * 并返回TRUE;否则返回FALSE*/
Status DeleteBST(BiTree *T,int key)
{
     if(!*T)    //不存在关键字等于key的数据元素
            return FALSE;
    else
    {
        if(key==(*T)->data)    //找到关键字等于key的数据元素
                return Delete(T);    //调用Delete函数删除该结点
        else if(key<(*T)->data)
                return DeleteBST(&(*T)->lchild,key);    
        else
                return DeleteBST(&(*T)->rchild,key);
    }   
}
Copy after login
(2)Delete删除算法
/*从二叉排序树中删除结点p,并重接它的左或右子树*/
Status Delete(BiTree *p)
{
     BiTree q,s;
    /*情况二:删除结点p的右子树或左子树为空*/
    if((*p)->lchild==NULL)               //a.右子树空则只需重接它的左子树
    {
            q=*p;    *p=(*p)->lchild;    free(q);
    }    
    else if((*p)->rchild==NULL)        //b.只需重接它的右子树
 【本文来自鸿网互联 (http://www.68idc.cn)】   {
            q=*p;    *p=(*p)->rchild;    free(q);    //将指针p指向的结点
    }
    //情况三:左右子树均不为空
    else
    {
            q=*p;    s=(*p)->lchild;
            while(s->rchild)            //转左,然后向右到尽头(找待删结点的前驱)
            {
                 q=s;    s=s->rchild;           
            }
            (*p)->data=s->data;    //s指向被删结点的直接前驱
            if(q!=*p)
                    q->rchild=s->lchild;    //重接q的右子树
            else
                    q->lchild=s->lchild;    //重接q的左子树
            free(s);
    }
    return TRUE;
}
Copy after login
源码分析: q=*p; *p=(*p)->rchild; free(q); 作用:将指针p指向的结点赋值给新结点q,并使p指针指向的左结点,即实现了重接右子树,再释放结点q.
三、二叉排序树总结 二叉排序树是以链接的方式存储,保持了链接存储结构在执行插入或删除操作时不用移动元素的优点,只要找到合适的插入和删除位置后,仅需修改链接指针即可。插入删除的时间性能比较好,而对于二叉排序树的查找,走的就是从根结点到要查找的结点的路径,其比较次数等于给定值的结点在二叉排序树的层数。极端情况,最少为1次,即跟结点就是要找的结点,最多也不会超过树的深度,即二叉排序树的查找性能取决于二叉排序树的形状。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use ddrescue to recover data on Linux Use ddrescue to recover data on Linux Mar 20, 2024 pm 01:37 PM

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training Mar 11, 2024 pm 12:10 PM

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects

Alibaba 7B multi-modal document understanding large model wins new SOTA Alibaba 7B multi-modal document understanding large model wins new SOTA Apr 02, 2024 am 11:31 AM

New SOTA for multimodal document understanding capabilities! Alibaba's mPLUG team released the latest open source work mPLUG-DocOwl1.5, which proposed a series of solutions to address the four major challenges of high-resolution image text recognition, general document structure understanding, instruction following, and introduction of external knowledge. Without further ado, let’s look at the effects first. One-click recognition and conversion of charts with complex structures into Markdown format: Charts of different styles are available: More detailed text recognition and positioning can also be easily handled: Detailed explanations of document understanding can also be given: You know, "Document Understanding" is currently An important scenario for the implementation of large language models. There are many products on the market to assist document reading. Some of them mainly use OCR systems for text recognition and cooperate with LLM for text processing.

See all articles