LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  TreeNode* deleteNode(TreeNode* root, int key) {
    if (!root) {
      return nullptr;
    }
    if (key > root->val) {
      root->right = deleteNode(root->right, key);
      return root;
    }
    if (key < root->val) {
      root->left = deleteNode(root->left, key);
      return root;
    }
    if (!root->left || !root->right) {
      TreeNode* t = root->left ? root->left : root->right;
      delete root;
      root = nullptr;
      return t;
    }
    TreeNode* t = root->right;
    while (t->left) {
      t = t->left;  // 右子树最左节点,即值大于根节点的下一节点
    }
    swap(root->val, t->val);
    root->right = deleteNode(root->right, key);
    return root;
  }
};