当前位置:网站首页>[template summary] - binary search tree BST - Basics
[template summary] - binary search tree BST - Basics
2022-07-03 22:08:00 【Ben potato】
Template Title Links
- BST lookup - Leetcode 270. Closest BST Value
- BST Insert - Leetcode 701. Insert Node in BST
- BST Delete - Leetcode 450. Delete Node in BST
Binary search tree -BST summary
BST It's a kind of binary tree , It has the structural properties of binary tree : only one Root node , Each node can have at most two child nodes .BST The nature of itself : The value of the left son of each node must be smaller than him , The value of the right son must be higher than him . This property also makes BST The output result of the middle order traversal of is a strictly increasing sequence . Strictly speaking ,BST Elements with the same value are not saved in , If there are duplicate elements, you can add them at each node count Property to count .
BST Basic inquiry template
- Find an element
according to BST Size relationship between left and right child nodes , You can directly use dichotomy for numerical queries , If the current value is smaller than the search value , Then look to the left , On the contrary, look to the right .
The code is as follows :
class Solution {
double min = Double.MAX_VALUE;
int res = -1;
public int closestValue(TreeNode root, double target) {
search(root, target);
return res;
}
private void search(TreeNode root, double target) {
// > target The first number of
if(root==null) return;
if(Math.abs(root.val-target)<min) {
min = Math.abs(root.val-target);
res = root.val;
}
if(root.val>target) search(root.left, target);
search(root.right, target);
}
}
Time complexity :, If BST The structure is relatively balanced ( Maximum height difference <=1) That is, balance BST Under the circumstances , The worst case scenario is possible BST The structure is very unbalanced , That is, all nodes form a similar linked list structure , At this time, the time will be
; Spatial complexity :
That is, the depth of recursion .
- BST Insert node
The idea of inserting nodes is easy to understand , We first find the position of leaf nodes where the values to be inserted can be inserted according to the size relationship , And establish new nodes and BST Just connect it

The code is as follows :
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode res = insert(root, val);
return res;
}
private TreeNode insert(TreeNode root, int val){
// Divide and conquer
if(root==null) return new TreeNode(val);
if(root.val<val) root.right = insert(root.right, val);
else if(root.val>val) root.left = insert(root.left, val);
return root;
}
}
- Delete node
Deleting a node is the most complicated of the basic queries , Because when deleting an element , For maintenance BST Ordered property of , You need to find a node to replace the location of the deleted node , And ensure that it will still be BST.
When deleting nodes again , There are three possibilities :
- The deleted node is a leaf node : In this case, delete the node directly
- Deleting a node only has left or right sons : In this case, directly connect the left or right son of the deleted node
- Deleting a node has left and right sons : This situation is the most complicated , These two kinds of nodes are usually used as replacement nodes : The largest point in the left subtree , perhaps The smallest point in the right subtree - That is, delete the point Forerunner (predecessor) and The subsequent nodes (successor). These two points are usually leaf nodes or only left or right sons ( Because they are the leftmost and right nodes on the subtree ) So replace the node to the position where the node is deleted , Directly connect its left or right subtree ( If any ).
- The largest point of the left subtree : That is, the rightmost point of the left subtree
- The smallest point of the right subtree : That is, the leftmost point of the right subtree


The code is as follows :
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode res = delete(root, key);
return res;
}
private TreeNode delete(TreeNode root, int key) {
if(root==null) return null;
if(root.val<key) root.right = delete(root.right, key);
else if(root.val>key) root.left = delete(root.left, key);
else {
// if root is leaf, directly remove
if(root.left==null && root.right==null) {
return null;
} else if(root.left!=null && root.right!=null) {
// find predecessor or successor to replace remove node
// predecessor - The maximum on the left
TreeNode left = root.left;
if(left.right==null) {
// no right node current node is predecessor
root.val = left.val;
root.left = left.left;
} else {
// To the right, find the rightmost, that is, the largest node and the largest node parent
// Here we use a fast and slow needle to find the corresponding position
TreeNode fast = left.right;
TreeNode slow = left;
while(fast.right!=null) {
fast = fast.right;
slow = slow.right;
}
// fast Find the far right ,slow Is the previous node
root.val = fast.val;
slow.right = fast.left; // remove predecessor
}
return root;
} else {
// one side is not leaf
if(root.left!=null) return root.left;
if(root.right!=null) return root.right;
}
}
return root;
}
}
Time complexity : If it is balance BST So that is , The worst :
; Spatial complexity :
Recursion depth .
边栏推荐
- 2022 high altitude installation, maintenance and removal of examination question bank and high altitude installation, maintenance and removal of examination papers
- Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
- 国泰君安证券开户是安全可靠的么?怎么开国泰君安证券账户
- pivot ROP Emporium
- Miscellaneous things that don't miss the right business
- 油猴插件
- Uboot migration
- JS Demo calcule combien de jours il reste de l'année
- What if the Flink SQL client exits and the table is emptied?
- gslb(global server load balance)技術的一點理解
猜你喜欢
On my first day at work, this API timeout optimization put me down!
(5) User login - services and processes - History Du touch date stat CP
2022 electrician (elementary) examination questions and electrician (elementary) registration examination
Blue Bridge Cup Guoxin Changtian single chip microcomputer -- software environment (II)
gslb(global server load balance)技术的一点理解
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
Redis single thread and multi thread
The latest analysis of crane driver (limited to bridge crane) in 2022 and the test questions and analysis of crane driver (limited to bridge crane)
QGIS grid processing DEM data reclassification
2022 safety officer-a certificate registration examination and summary of safety officer-a certificate examination
随机推荐
gslb(global server load balance)技术的一点理解
DR-NAS26-Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-5GHz-high-power-Mini-PCIe-Wi-Fi-Module
90 後,辭職創業,說要卷死雲數據庫
Cognitive fallacy: Wittgenstein's ruler
DOM light switch case
油猴插件
Mysql database - Advanced SQL statement (I)
4. Data splitting of Flink real-time project
QGIS grid processing DEM data reclassification
MySQL - idea connects to MySQL
Morning flowers and evening flowers
Sed、Awk
Yiwen teaches you how to choose your own NFT trading market
Electronic tube: Literature Research on basic characteristics of 6j1
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
How PHP adds two numbers
js demo 计算本年度还剩下多少天
十大券商开户注册安全靠谱吗?有没有风险的?
treevalue——Master Nested Data Like Tensor
China's TPMS industry demand forecast and future development trend analysis report Ⓐ 2022 ~ 2028