https://leetcode.com/problems/delete-node-in-a-bst/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) {
return root;
}
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 && root->right) {
TreeNode* node = findMin(root->right);
root->val = node->val;
root->right = deleteNode(root->right, node->val);
} else {
root = root->left ? root->left : root->right;
}
}
return root;
}
TreeNode* findMin(TreeNode* root) {
if (!root) {
return root;
}
while(root->left) {
root = root->left;
}
return root;
}
};