当前位置:网站首页>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

边栏推荐
- 请问创建MySQL数据源资源组必须要选择新建独享数据集成资源组才可用?还是使用公共资源组就可以?谢谢
- 落实责任到人,广州多措并举筑牢儿童暑期“安全线”
- rxbinding
- Cumulative output data of kettle Excel
- I want to consult. Our maxcompute spark program needs to access redis, development environment and production environment redis
- HDU1171_Big Event in HDU【01背包】
- Yanghui triangle
- ReferenceError: __dirname is not defined in ES module scope
- C language: 10. Input stream, output stream, error stream
- ReferenceError: __ dirname is not defined in ES module scope
猜你喜欢

IPFs obtains the public key and private key through the interface, and encrypts the storage. First bullet

S32k series chips -- Introduction

Introduction to Flink operator

C language: 14. Preprocessing

Under the heat wave of Web3.0, the ecological shock of Mensa struck

Low code implementation exploration (45) business parameters

influxDB系列(四)TSM引擎(存储原理)

Debian recaptured the "debian.community" domain name, but it's still not good to stop and rest

Memory management A4

来一遍《剑指Offer》03. 数组中重复的数字
随机推荐
让你的聊天气泡丰富多彩
Original pw4203 step-down 1-3 lithium battery charging chip
SQLServer 2008中事务日志已满问题处理
c语言:5、多维数组
Map和Set
低代码实现探索(四十五)业务参数
Basic network faults and troubleshooting
Low code implementation exploration (45) business parameters
嵌入式C语言循环展开
来一遍《剑指Offer》03. 数组中重复的数字
C language: 14. Preprocessing
【日常积累 - 06】查看cuda和cudnn版本
【深度学习基础知识 - 44】逻辑回归实现多分类的方法
go-zero单体服务使用泛型简化注册Handler路由
4 轮拿下字节 Offer,面试题复盘
opds sql 里面可以用set 定义局部变量吗
[basic knowledge of deep learning - 43] concept of odds ratio
一种比读写锁更快的锁,还不赶紧认识一下
VIVO应用市场APP上架总结
C language: C language code style
