跳转至

删除二叉搜索树中的节点⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (!root) return nullptr;

        if (root->val == key) {
            if (!root->left && !root->right) {
                delete root;
                return nullptr;
            } else if (!root->left) {
                auto res = root->right;
                delete root;
                return res;
            } else if (!root->right) {
                auto res = root->left;
                delete root;
                return res;
            } else { // root->left != nullptr && root->right != nullptr
                auto curr = root->right;
                while (curr->left) {
                    curr = curr->left;
                }
                curr->left = root->left;

                auto temp = root;
                root = root->right;
                delete temp;
                return root;
            }
        }

        if (root->val > key) root->left = deleteNode(root->left, key);
        if (root->val < key) root->right = deleteNode(root->right, key);

        return root;
    }
};