-
Notifications
You must be signed in to change notification settings - Fork 18
/
Delete Node in a Binary Search Treee
50 lines (50 loc) · 1.42 KB
/
Delete Node in a Binary Search Treee
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
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == NULL) {
return NULL;
}
if (root->val == key) {
return helper(root);
}
TreeNode *dummy = root;
while (root != NULL) {
if (root->val > key) {
if (root->left != NULL && root->left->val == key) {
root->left = helper(root->left);
break;
} else {
root = root->left;
}
} else {
if (root->right != NULL && root->right->val == key) {
root->right = helper(root->right);
break;
} else {
root = root->right;
}
}
}
return dummy;
}
TreeNode* helper(TreeNode* root) {
if (root->left == NULL)
{
return root->right;
}
else if (root->right == NULL)
{
return root->left;
}
TreeNode* rightChild = root->right;
TreeNode* lastRight = findLastRight(root->left);
lastRight->right = rightChild;
return root->left;
}
TreeNode* findLastRight(TreeNode* root) {
if (root->right == NULL) {
return root;
}
return findLastRight(root->right);
}
};