当前位置:网站首页>[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 .
边栏推荐
- Yyds dry inventory Chapter 4 of getting started with MySQL: data types that can be stored in the data table
- Is it safe and reliable to open an account and register for stock speculation? Is there any risk?
- Global and Chinese market of telematics boxes 2022-2028: Research Report on technology, participants, trends, market size and share
- Capturing and sorting out external articles -- autoresponder, composer, statistics [III]
- Global and Chinese market of AC induction motors 2022-2028: Research Report on technology, participants, trends, market size and share
- Miscellaneous things that don't miss the right business
- Rest reference
- Intimacy communication -- [repair relationship] - use communication to heal injuries
- pivot ROP Emporium
- Blue Bridge Cup Guoxin Changtian single chip microcomputer -- led lamp module (V)
猜你喜欢

Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
![Intimacy communication -- [repair relationship] - use communication to heal injuries](/img/c2/f10405e3caf570dc6bd124d65b2e93.jpg)
Intimacy communication -- [repair relationship] - use communication to heal injuries

Dahua series books

The latest analysis of R1 quick opening pressure vessel operation in 2022 and the examination question bank of R1 quick opening pressure vessel operation

2022 safety officer-b certificate examination summary and safety officer-b certificate simulation test questions

What should the future of the Internet be like when Silicon Valley employees flee the big factory and rush to Web3| Footprint Analytics

Décompiler et modifier un exe ou une DLL non source en utilisant dnspy

How PHP adds two numbers

Data consistency between redis and database

90 後,辭職創業,說要卷死雲數據庫
随机推荐
Luogu deep foundation part 1 Introduction to language Chapter 7 functions and structures
油猴插件
DOM light switch case
Blue Bridge Cup Guoxin Changtian single chip microcomputer -- software environment (II)
Yiwen teaches you how to choose your own NFT trading market
Collection | pytoch common loss function disassembly
The latest analysis of R1 quick opening pressure vessel operation in 2022 and the examination question bank of R1 quick opening pressure vessel operation
English topic assignment (28)
How PHP adds two numbers
Dahua series books
Introduction to kubernetes
油猴插件
Implementation principle of inheritance, encapsulation and polymorphism
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)
Global and Chinese market of telematics boxes 2022-2028: Research Report on technology, participants, trends, market size and share
Yyds dry inventory Chapter 4 of getting started with MySQL: data types that can be stored in the data table
Morning flowers and evening flowers
Asynchronous artifact: implementation principle and usage scenario of completable future
DR-NAS26-Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-5GHz-high-power-Mini-PCIe-Wi-Fi-Module
Investment analysis and prospect trend prediction report of China's boron nitride industry Ⓨ 2022 ~ 2028