#3832. [GESP202509 六级 C++] 第 14 题

[GESP202509 六级 C++] 第 14 题

删除二叉排序树中的节点时,如果节点有两个孩子,则横线处应填入( ),其中 findMaxfindMin 分别为寻找树的最大值和最小值的函数。

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};

TreeNode* deleteNode(TreeNode* root, int key) {
    if (!root) return nullptr;
    if (key < root->val) {
        root->left = deleteNode(root->left, key);
    }
    else if (key > root->val) {
        root->right = deleteNode(root->right, key);
    }
    else {
        if (!root->left) return root->right;
        if (!root->right) return root->left;
        TreeNode* temp = ____________;          // 在此处填写代码
        root->val = temp->val;
        root->right = deleteNode(root->right, temp->val);
    }
    return root;
}

{{ select(1) }}

  • root->left
  • root->right
  • findMin(root->right)
  • findMax(root->left)