-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path450.cpp
More file actions
69 lines (69 loc) · 2.46 KB
/
Copy path450.cpp
File metadata and controls
69 lines (69 loc) · 2.46 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
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
public:
TreeNode *deleteNode(TreeNode *root, int key) {
if (!root)
return nullptr;
auto ret = root;
if (root->val == key) {
if (!root->right)
return root->left;
else if (!root->left)
return root->right;
auto right_left = root->right;
while (right_left->left)
right_left = right_left->left;
right_left->left = root->left->right;
root->left->right = root->right;
return root->left;
}
auto prev = root;
while (root) {
if (root->val < key) {
prev = root;
root = root->right;
} else if (root->val > key) {
prev = root;
root = root->left;
} else {
if (root == prev->left) {
if (!root->left && !root->right) {
prev->left = nullptr;
return ret;
} else if (!root->left) {
prev->left = root->right;
return ret;
} else if (!root->right) {
prev->left = root->left;
return ret;
}
auto right_left = root->right;
while (right_left->left)
right_left = right_left->left;
right_left->left = root->left->right;
root->left->right = root->right;
prev->left = root->left;
return ret;
} else {
if (!root->left && !root->right) {
prev->right = nullptr;
return ret;
} else if (!root->left) {
prev->right = root->right;
return ret;
} else if (!root->right) {
prev->right = root->left;
return ret;
}
auto right_left = root->right;
while (right_left->left)
right_left = right_left->left;
right_left->left = root->left->right;
root->left->right = root->right;
prev->right = root->left;
return ret;
}
}
}
return ret;
}
};