Untitled
unknown
plain_text
2 years ago
1.2 kB
5
Indexable
/**
* 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) {
if(root==nullptr) return root;
if(key<root->val){
root->left=deleteNode(root->left,key);
}else if(key >root->val){
root->right=deleteNode(root->right,key);
}
else if(key ==root->val){ //we found the node , now replace it with the min value from right subtree and recursively delete the min value
if(!root->left) return root->right;
else if(!root->right) return root->left;
else if(root->left && root->right){
TreeNode* tmp=root->right;
while(tmp->left) tmp=tmp->left;
root->val=tmp->val;
root->right=deleteNode(root->right,tmp->val);
}
}
return root;
}
};Editor is loading...
Leave a Comment