# Untitled

unknown
plain_text
a month ago
1.7 kB
1
Indexable
Never
```/**
* 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 {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
// cout << root->val << endl;
if (!root) {
return root;
}
if (root->val == key) {
TreeNode *left = root->left;
TreeNode *right = root->right;
TreeNode *initialRight = right;
if (!right) {
return left;
}
if (!left) {
return right;
}
TreeNode *parent = NULL;
while (right->left) {
cout << right->left->val << " loop was run" << endl;
parent = right;
right = right->left;
}
cout << "LOOP ENDED" << endl;
TreeNode *smallestRight = right->right;

if (parent) {
cout << "Parent was set << endl" << endl;
parent->left = smallestRight;
}

delete root;

if (right != initialRight) {
right->right = initialRight;
}
right->left = left;
return right;
}
if (root->val < key) {
root->right = deleteNode(root->right, key);
} else {
root->left = deleteNode(root->left, key);
}
return root;
}
};```