当前位置:网站首页>[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 .
边栏推荐
- Global and Chinese market of gallic acid 2022-2028: Research Report on technology, participants, trends, market size and share
- What should the future of the Internet be like when Silicon Valley employees flee the big factory and rush to Web3| Footprint Analytics
- Market layout planning and latest dynamic analysis report of China's smart public security industry Ⓕ 2022 ~ 2028
- Pengcheng cup Web_ WP
- How does sentinel, a traffic management artifact, make it easy for business parties to access?
- [secretly kill little partner pytorch20 days] - [day3] - [example of text data modeling process]
- Cognitive fallacy: what is dimensional curse
- Collection | pytoch common loss function disassembly
- MySQL——JDBC
- 十大券商开户注册安全靠谱吗?有没有风险的?
猜你喜欢

gslb(global server load balance)技術的一點理解

How PHP drives mongodb

Mysql database - Advanced SQL statement (I)

Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?

Station B, dark horse programmer, employee management system, access conflict related (there is an unhandled exception at 0x00007ff633a4c54d (in employee management system.Exe): 0xc0000005: read locat

QGIS grid processing DEM data reclassification

Introduction to kubernetes

Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?

UC Berkeley proposes a multitask framework slip

Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
随机推荐
Leetcode problem solving - 235 Nearest common ancestor of binary search tree
Redis single thread and multi thread
Mysql database - Advanced SQL statement (I)
Common SQL sets
What indicators should be paid attention to in current limit monitoring?
Conditional statements of shell programming
How to store null value on the disk of yyds dry inventory?
Yyds dry inventory Chapter 4 of getting started with MySQL: data types that can be stored in the data table
The latest analysis of R1 quick opening pressure vessel operation in 2022 and the examination question bank of R1 quick opening pressure vessel operation
油猴插件
Farmersworld farmers world, no faith, how to talk about success?
regular expression
Station B, dark horse programmer, employee management system, access conflict related (there is an unhandled exception at 0x00007ff633a4c54d (in employee management system.Exe): 0xc0000005: read locat
Cognitive fallacy: what is Fredkin's paradox
How to install sentinel console
Uboot migration
Persistence of Nacos
Global and Chinese market of wall mounted kiosks 2022-2028: Research Report on technology, participants, trends, market size and share
股票炒股开户注册安全靠谱吗?有没有风险的?
2022-02-15 Daily: 2022 AAAI fellow release