-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathDelete_Node_BST.cpp
63 lines (60 loc) · 1.67 KB
/
Delete_Node_BST.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
// Definition for a binary tree node.
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 {
TreeNode *leftLastRight(TreeNode* temp)
{
if (temp->right == NULL)
return temp;
return leftLastRight(temp->right);
}
TreeNode* forRight(TreeNode* temp)
{
if (temp->left == NULL)
return temp->right;
else if (temp->right == NULL)
return temp->left;
TreeNode* tempRight = temp->right;
TreeNode* lastRight = leftLastRight(temp->left);
lastRight->right = tempRight;
return temp->left;
}
public:
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode *temp = root;
if (temp == NULL)
return NULL;
else if (temp->val == key)
{
return forRight(temp);
}
while (temp != NULL)
{
if (temp->left != NULL && temp->left->val == key)
{
temp->left = forRight(temp->left);
return root;
}
else if (temp->right != NULL && temp->right->val == key)
{
temp->right = forRight(temp->right);
return root;
}
else if (temp->left != NULL && temp->val > key)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
return root;
}
};