Skip to content

Commit

Permalink
450. Delete Node in a BST
Browse files Browse the repository at this point in the history
  • Loading branch information
gzc authored Oct 3, 2021
1 parent d4a885f commit ab73850
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions cpp/441-450/Delete Node in a BST.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
Expand All @@ -20,11 +21,18 @@ class Solution {
TreeNode* right = root->right;
while (right->left)
right = right->left;
swap(root->val, right->val);
swap(root->val, right->val);
root->right = deleteNode(root->right, key);
return root;
}
}
root->left = deleteNode(root->left, key);
root->right = deleteNode(root->right, key);

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

return root;
}
};

0 comments on commit ab73850

Please sign in to comment.