-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-node-in-binary-search-tree.cpp
71 lines (59 loc) · 2.16 KB
/
remove-node-in-binary-search-tree.cpp
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
70
71
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
void replaceInParent(TreeNode *parent, TreeNode *node, TreeNode *replacement) {
if (!parent) return;
//cout << "replacing " << node->val << " in parent " << parent->val << " with " << (replacement ? to_string(replacement->val) : "null") << endl;
if (parent->left == node) parent->left = replacement;
else if(parent->right == node) parent->right = replacement;
}
void removeNode(TreeNode *node, TreeNode *parent, int value) {
if (!node) return;
//cout << "in node " << node->val << " of parent " << parent->val << endl;
if (node->val == value) {
if (!node->left && !node->right) {
replaceInParent(parent, node, nullptr);
} else if (node->left && !node->right) {
replaceInParent(parent, node, node->left);
} else if (node->right && !node->left) {
replaceInParent(parent, node, node->right);
} else {
TreeNode *current = node->right;
TreeNode *currentParent = node;
while (current->left) {
currentParent = current;
current = current->left;
}
node->val = current->val;
replaceInParent(currentParent, current, nullptr);
}
} else if (node->val < value) {
removeNode(node->right, node, value);
} else {
removeNode(node->left, node, value);
}
}
public:
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
TreeNode* removeNode(TreeNode* root, int value) {
if (!root) return root;
TreeNode *dummyRoot = new TreeNode(-1);
dummyRoot->left = root;
removeNode(root, dummyRoot, value);
return dummyRoot->left;
}
};