leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0450.cpp (918B)


0 class Solution {
1 TreeNode *deleteRoot(TreeNode *root) {
2 if (!root) return nullptr;
3 if (!root->left) return root->right;
4 if (!root->right) return root->left;
6 TreeNode *next = root->right;
7 TreeNode *pre = nullptr;
8 while (next->left) {
9 pre = next;
10 next = next->left;
11 }
12 next->left = root->left;
13 if (root->right != next) {
14 pre->left = next->right;
15 next->right = root->right;
16 }
17 return next;
18 }
20 public:
21 TreeNode *deleteNode(TreeNode *root, int key) {
22 TreeNode *cur = root, *pre = nullptr;
23 while (cur && cur->val != key) {
24 pre = cur;
25 cur = key < cur->val ? cur->left : cur->right;
26 }
28 if (!pre) return deleteRoot(cur);
29 (pre->left == cur ? pre->left : pre->right) = deleteRoot(cur);
30 return root;
31 }
32 };