-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path450.cpp
More file actions
57 lines (49 loc) · 1.51 KB
/
Copy path450.cpp
File metadata and controls
57 lines (49 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 (root->val == key)
return helper(root);
TreeNode* dummy = root;
while (root) {
if (root->val > key) {
if (root->left && root->left->val == key) {
root->left = helper(root->left);
break;
} else {
root = root->left;
}
} else {
if (root->right && root->right->val == key) {
root->right = helper(root->right);
break;
} else {
root = root->right;
}
}
}
return dummy;
}
TreeNode* helper(TreeNode* root) {
if (root->left == nullptr)
return root->right;
if (root->right == nullptr)
return root->left;
TreeNode* rc = root->right;
TreeNode* lastRight = findLastRight(root->left);
lastRight->right = rc;
return root->left;
}
TreeNode* findLastRight(TreeNode* root) {
if (!root->right) return root;
return findLastRight(root->right);
}
};