当前位置:网站首页>[450. delete nodes in binary search tree]
[450. delete nodes in binary search tree]
2022-06-30 22:13:00 【Sugar_ wolf】
source : Power button (LeetCode)
describe :
Given the root node of a binary search tree root And a value key, Delete the key Corresponding node , And keep the property of binary search tree unchanged . Back to binary search tree ( May be updated ) Reference to the root node of .
Generally speaking , Deleting a node can be divided into two steps :
First find the node to be deleted ;
If you find it , Delete it .
Example 1:
Input :root = [5,3,6,2,4,null,7], key = 3
Output :[5,4,6,2,null,null,7]
explain : Given the node value to be deleted is 3, So first we found 3 This node , Then delete it .
The right answer is [5,4,6,2,null,null,7], As shown in the figure below .
The other correct answer is [5,2,6,null,4,null,7].
Example 2:
Input : root = [5,3,6,2,4,null,7], key = 0
Output : [5,3,6,2,4,null,7]
explain : Binary tree does not contain a value of 0 The node of
Example 3:
Input : root = [], key = 0
Output : []
Tips :
- Range of nodes [0, 104].
- -105<= Node.val <= 105
- Unique node value
- root Is a legitimate binary search tree
- -105 <= key <= 105
Method 1 : recursive
Ideas
Code :
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) {
return nullptr;
}
if (root->val > key) {
root->left = deleteNode(root->left, key);
return root;
}
if (root->val < key) {
root->right = deleteNode(root->right, key);
return root;
}
if (root->val == key) {
if (!root->left && !root->right) {
return nullptr;
}
if (!root->right) {
return root->left;
}
if (!root->left) {
return root->right;
}
TreeNode *successor = root->right;
while (successor->left) {
successor = successor->left;
}
root->right = deleteNode(root->right, successor->val);
successor->right = root->right;
successor->left = root->left;
return successor;
}
return root;
}
};
Execution time :28 ms, In all C++ Defeated in submission 83.08% Users of
Memory consumption :31.8 MB, In all C++ Defeated in submission 71.37% Users of
Complexity analysis
Time complexity : O(n), among n by root Number of nodes . In the worst case , Find and delete successor Each tree needs to be traversed once .
Spatial complexity : O(n), among n by root Number of nodes . The deepest recursion is O(n).
Method 2 : iteration
Ideas
The recursion depth of method 1 is at most n, And most of it is by looking for a value of key The contribution of the node , The part of finding nodes can be optimized by iteration . Find and delete successor when , You can also save its parent node with a variable , Thus, one step recursive operation can be saved .
Code :
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode *cur = root, *curParent = nullptr;
while (cur && cur->val != key) {
curParent = cur;
if (cur->val > key) {
cur = cur->left;
} else {
cur = cur->right;
}
}
if (!cur) {
return root;
}
if (!cur->left && !cur->right) {
cur = nullptr;
} else if (!cur->right) {
cur = cur->left;
} else if (!cur->left) {
cur = cur->right;
} else {
TreeNode *successor = cur->right, *successorParent = cur;
while (successor->left) {
successorParent = successor;
successor = successor->left;
}
if (successorParent->val == cur->val) {
successorParent->right = successor->right;
} else {
successorParent->left = successor->right;
}
successor->right = cur->right;
successor->left = cur->left;
cur = successor;
}
if (!curParent) {
return cur;
} else {
if (curParent->left && curParent->left->val == key) {
curParent->left = cur;
} else {
curParent->right = cur;
}
return root;
}
}
};
Execution time :28 ms, In all C++ Defeated in submission 83.08% Users of
Memory consumption :31.8 MB, In all C++ Defeated in submission 86.56% Users of
Complexity analysis
Time complexity : O(n), among n by root Number of nodes . In the worst case , You need to traverse the tree once .
Spatial complexity : O(1). The space used is constant .
author:LeetCode-Solution
边栏推荐
- JVM Part 21 of interview with big companies Q & A
- PyTorch量化实践(2)
- Vite2 is compatible with lower versions of chrome (such as Sogou 80). Some grammars requiring higher versions are processed through polyfills
- Tencent has been conducting advanced automated functional testing for 3 years. It is a gift to you who are confused in manual testing
- 去中心化交易所系统开发技术原理丨数字货币去中心化交易所系统开发(说明案例)
- JD and Tencent renewed the three-year strategic cooperation agreement; The starting salary rose to 260000 yuan, and Samsung sk of South Korea scrambled for a raise to retain semiconductor talents; Fir
- 【回溯】全排列 II leetcode47
- Introduction to go web programming: a probe into the excellent test library gocovey
- Stinky tofu made by Grandma
- What is the experience of pairing with AI? Pilot vs alphacode, Codex, gpt-3
猜你喜欢
Win11电脑名如何更改?Win11更改电脑名的方法
Is Wu Enda's machine learning suitable for entry?
JVM Part 21 of interview with big companies Q & A
WinDbg debugging tool introduction
On several key issues of digital transformation
Which direction should college students choose to find jobs after graduation?
Rethink healthy diet based on intestinal microbiome
How to upload binary pictures in uniapp
Is there a shortage? No need to download the free online resources! 2022 favorites must have it!
B_ QuRT_ User_ Guide(32)
随机推荐
Windbg调试工具介绍
Error filesystemexception: /data/nodes/0/indices/gttxk-hntgkhacm-8n60jw/1/index/ es_ temp_ File: structure needs cleaning
Look at the top 10 capabilities of alicloud cipu
交易所系统开发如何开发?数字货币交易所系统开发成熟技术案例
[backtracking] full arrangement leetcode46
"Trust machine" empowers development
【BSP视频教程】BSP视频教程第19期:单片机BootLoader的AES加密实战,含上位机和下位机代码全开源(2022-06-26)
Nansen复盘加密巨头自救:如何阻止百亿多米诺倾塌
Pytorch quantitative practice (2)
机器学习适合女生学吗?
顺祝老吴的聚会
Anfulai embedded weekly report no. 271: June 20, 2022 to June 26, 2022
How to judge whether the JS object is empty
《安富莱嵌入式周报》第270期:2022.06.13--2022.06.19
Do a scrollbar thinking
How to realize the center progress bar in wechat applet
Ml & DL: introduction to hyperparametric optimization in machine learning and deep learning, evaluation index, over fitting phenomenon, and detailed introduction to commonly used parameter adjustment
RP prototype resource sharing - shopping app
On several key issues of digital transformation
Uniapp life cycle / route jump