This commit is contained in:
Sainnhe Park 2023-02-01 11:42:09 +08:00
parent 8c694f2996
commit a0517aa4d0
3 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,11 @@
#ifndef S0450_DELETE_NODE_IN_A_BST_HPP
#define S0450_DELETE_NODE_IN_A_BST_HPP
#include "structures.hpp"
class S0450 {
public:
TreeNode* deleteNode(TreeNode* root, int key);
};
#endif

View File

@ -2,3 +2,4 @@
- [s0235](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/): 找两个指定节点的最近公共祖先。思路很简单,只要出现分岔(即一个在当前节点的左边,一个在当前节点的右边),那么这个分岔点就是最近公共祖先。
- [s0701](https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/): 插入节点。一层一层往下找,直到发现找不到了就在这个地方插入。
- [s0450](https://leetcode.cn/problems/delete-node-in-a-bst/description/): 删除节点。递归删除。

View File

@ -0,0 +1,30 @@
#include "s0450_delete_node_in_a_bst.hpp"
TreeNode* S0450::deleteNode(TreeNode* root, int key) {
// 如果根节点为空,则直接返回
if (root == nullptr) return nullptr;
// 如果 key 等于根节点的值,则删除根节点,并将左子树的最右侧节点提上来
if (root->val == key) {
// 左子树为空的情况
if (root->left == nullptr) {
return root->right;
} else { // 左子树不为空时
// 找到左子树的最右侧节点
TreeNode *cur = root->left;
while (cur->right) {
cur = cur->right;
}
// 把这个节点提上来,并删除左子树中的该节点
cur->left = deleteNode(root->left, cur->val);
cur->right = root->right;
// 返回
return cur;
}
} else if (key < root->val) {
root->left = deleteNode(root->left, key);
return root;
} else {
root->right = deleteNode(root->right, key);
return root;
}
}