450. Delete Node in a BST Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. 1234567891011121314151617181920212223242526272829303132/** * 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(key == root->val) { TreeNode *l = root->left, *r = root->right; if(!l and !r) return nullptr; if(l and r) { TreeNode* res = r; while(r->left) r = r->left; r->left = l; return res; } else if(l) return l; else return r; } else { if(root->val > key) root->left = deleteNode(root->left, key); else root->right = deleteNode(root->right, key); return root; } }};