当前位置:网站首页>Binary search tree
Binary search tree
2022-07-27 19:42:00 【Warm the sun like the wind】


️ Preface ️
This article —— Binary search tree is both a pair of previous articles 【 Trees and binary trees 】 Some supplements to , Also for follow-up articles TreeMap and TreeSet Bedding of interface introduction .
Blog home page :【 Warm the sun like the wind 】
The high-quality goods Java special column 【JavaSE】、【 Prepare for blue bridge 】、【JavaEE The first step 】、【MySQL】、【 data structure 】
Welcome to thumb up Collection Leave a comment Private letters must be answeredThis paper is written by 【 Warm the sun like the wind 】 original , First appeared in CSDN
Bloggers will continue to update their learning records and gain , If you have any questions, you can leave a message in the comment area
The source code involved in the blog and the daily practice code of the blogger have been uploaded Code cloud (gitee)、GitHub
Here I would like to recommend some websites that bloggers often use to brush questions 【 Cattle from 】, The finger of the sword Offer The column is a high-frequency list of written interview questions , Let's brush it up !

Content guide

Binary search tree
1. Concept
Binary search tree is also called binary sort tree , It could be an empty tree , Or a binary tree with the following properties :
- If its left subtree is not empty , Then the values of all nodes on the left subtree are smaller than the values of the root nodes
- If its right subtree is not empty , Then the value of all nodes on the right subtree is greater than the value of the root node
- Its left and right subtrees are also binary search trees
- The middle order traversal result of binary search tree is ordered
As shown in the figure below, it is a binary search tree 
First, complete the basic construction of binary search tree through code :
public class BinarySearchTree {
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode root;
}
2. Search operation
Find key values in the search tree , Because of the characteristics of binary search tree , So you can compare the key value with the root node value , If it is smaller than the root node , Go to the left sub tree to find , On the contrary, go to the right subtree to find .
public TreeNode search(int key) {
TreeNode cur=root;
while (cur!=null) {
if(cur.val<key) {
cur=cur.right;
}else if(cur.val>key) {
cur=cur.left;
}else {
return cur;
}
}
// If you go here, you won't find the keyword
return null;
}
3. The insert
The insertion operation still follows the characteristics of binary search tree , Compare with the root node value , If it is smaller than it, insert it into the left subtree , If it is larger than it, insert it into the right subtree , You can find , Finally, they are inserted into the leaf node . Because the insertion operation requires that the previous node has a reference to the insertion node , So you need to use two nodes .
public boolean insert(int key) {
TreeNode node=new TreeNode(key);
// Empty tree direct insertion
if(root==null) {
root=node;
return true;
}
TreeNode cur=root;
TreeNode parent=null;// Used to store the reference of the previous node
while (cur!=null) {
if(cur.val<key) {
parent=cur;
cur=cur.right;
}else if(cur.val>key) {
parent=cur;
cur=cur.left;
}else {
// There are the same elements Cannot insert successfully
return false;
}
}
// Code goes here ,cur==null, According to the previous node parent Of val Comparison , Determine whether to insert the left or right of the node
if(parent.val<key) {
parent.right=node;
}else {
parent.left=node;
}
return true;
}
4. Delete operation
The deletion of binary search tree is very complex , First, you need to find the node to delete , But this node may have left and right subtrees , So you can't just delete it , You need to determine the specific deletion method according to the situation , as follows :
Set the node to be deleted as cur, The parent node of the node to be deleted is parent
1.cur.left == null
- cur yes root, be root = cur.right
- cur No root,cur yes parent.left, be parent.left = cur.right
- cur No root,cur yes parent.right, be parent.right = cur.right
2.cur.right == null
- cur yes root, be root = cur.left
- cur No root,cur yes parent.left, be parent.left = cur.left
- cur No root,cur yes parent.right, be parent.right = cur.left
3.cur.left != null && cur.right != null
You need to use substitution to delete , That is to say Find the minimum value in its right subtree ( It must have no left tree )【 Or find the maximum value in its left subtree , It must have no right tree 】, Fill the deleted node with its value , Then deal with the deletion of this node ( Handle the node and the situation 1 identical , There is no left subtree )
Code implementation :
/** * Delete the keyword as key The node of * @param key */
public void remove(int key) {
// Find the node first
TreeNode cur=root;
TreeNode parent=null;
while (cur!=null) {
if(cur.val<key) {
parent=cur;
cur=cur.right;
}else if(cur.val>key) {
parent=cur;
cur=cur.left;
}else {
// The code goes here to indicate that the node to be deleted is found
removeNode(cur,parent);
}
}
}
/** * To delete * @param cur The node to be deleted * @param parent Delete the parent of the node */
private void removeNode(TreeNode cur,TreeNode parent) {
if(cur.left==null) {
if(cur==root) {
root=root.right;
}else if(cur==parent.left) {
parent.left=cur.right;
}else {
parent.right=cur.right;
}
}else if(cur.right==null) {
if(cur==root) {
root=root.left;
}else if(cur==parent.left) {
parent.left=cur.left;
}else {
parent.right=cur.left;
}
}else {
TreeNode targetParent=cur;// Record the previous node of the node used for replacement
TreeNode target=cur.right;// Record the nodes used for replacement
// Find the minimum value in the right subtree , Just go straight to the left , The node at the end is the minimum
while (target.left!=null) {
targetParent=target;
target=target.left;
}
// Find the node to replace , Complete replacement of values , Then deal with deleting the replacement node
cur.val=target.val;
// At this time, the node must have no left subtree , The deletion method is the same as the previous one without left subtree
if(targetParent.left==target) {
targetParent.left=target.right;
}else {
targetParent.right=target.right;
}
}
}
5. Performance analysis
The insertion and deletion operations of binary search tree need progressiveness search , Search efficiency represents the performance of each operation in binary search tree , According to different insertion order , The resulting binary tree structure may also be different .
Best case :
Get a complete binary tree
The time complexity of the search is O( l o g 2 N log_2N log2N)
Worst case scenario :
Get a single branch tree
The time complexity of the search is O(N)
TreeMap and TreeSet ( These two interfaces are introduced in the following article ) namely java Using search tree to achieve Map and Set; In fact, it uses red and black trees , The red black tree is an approximately balanced binary search tree , That is, based on the binary search tree + Color and red black tree property verification , The content of red black tree will be explained later .
️ Last words ️
Summing up difficulties , hope uu Don't be stingy with your (^U^)ノ~YO!! If there is a problem , Welcome comments and corrections in the comment area

边栏推荐
- 【深度学习基础知识 - 45】机器学习中常用的距离计算方法
- Memory management A4
- Incluxdb series (III) detailed explanation of incluxdb configuration file
- C language: 13. Pointer and memory
- Kettle learning - the repository configuration in version 8.2 is grayed out, and there is no connect button
- IIS 发生未知FastCGI错误:0x80070005
- 传苹果计划以2亿美元购买JDI部分工厂
- 台积电5nm即将量产:苹果A14独占7成产能,华为麒麟1020拿下3成
- C language: C language code style
- C language: 12. GDB tool debugging C program
猜你喜欢

Flink简介以及运行架构

Original pw4203 step-down 1-3 lithium battery charging chip

C language: 7. How to use C language multi source files

Webmagic+selenium+chromedriver+jdbc grabs data vertically.

Cumulative output data of kettle Excel

Kettle consolidated record data reduction

二叉搜索树

Kettle8.2 installation and common problems

VIVO应用市场APP上架总结

C language: 11. Pipeline
随机推荐
To create a MySQL data source resource group, you must choose to create a new exclusive data integration resource group? Or use a common resource group? thank you
Kettle JVM memory setting - the effect is not obvious
王牌代码静态测试工具Helix QAC 2022.2中的新增功能(2)
请问创建MySQL数据源资源组必须要选择新建独享数据集成资源组才可用?还是使用公共资源组就可以?谢谢
c语言:14、预处理
c语言:12、gdb工具调试c程序
揭秘高通超声波指纹被“贴膜破解”之谜
Anaconda下安装Talib库
【深度学习基础知识 - 49】Kmeans
Under the heat wave of Web3.0, the ecological shock of Mensa struck
Map和Set
应用程序池已被禁用
c语言:clion调试方法
英特尔未来10年工艺路线图曝光:2029年推出1.4nm工艺!如何实现?
rxbinding
Dry goods of technical practice | preliminary exploration of large-scale gbdt training
influxDB系列(三)influxDB配置文件详解
技术实践干货 | 初探大规模 GBDT 训练
go-zero单体服务使用泛型简化注册Handler路由
Matplotlib(基本用法)
