From a0517aa4d00437313061f0c05f3dd0ebc6fdd001 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 1 Feb 2023 11:42:09 +0800 Subject: [PATCH] s0450 --- include/s0450_delete_node_in_a_bst.hpp | 11 ++++++++++ notes/src/bstree.md | 1 + src/s0450_delete_node_in_a_bst.cpp | 30 ++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 include/s0450_delete_node_in_a_bst.hpp create mode 100644 src/s0450_delete_node_in_a_bst.cpp diff --git a/include/s0450_delete_node_in_a_bst.hpp b/include/s0450_delete_node_in_a_bst.hpp new file mode 100644 index 0000000..6dbd90f --- /dev/null +++ b/include/s0450_delete_node_in_a_bst.hpp @@ -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 diff --git a/notes/src/bstree.md b/notes/src/bstree.md index d4e75e3..dc24e74 100644 --- a/notes/src/bstree.md +++ b/notes/src/bstree.md @@ -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/): 删除节点。递归删除。 diff --git a/src/s0450_delete_node_in_a_bst.cpp b/src/s0450_delete_node_in_a_bst.cpp new file mode 100644 index 0000000..d8e67b3 --- /dev/null +++ b/src/s0450_delete_node_in_a_bst.cpp @@ -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; + } +}