forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0450.cpp
More file actions
executable file
·36 lines (31 loc) · 732 Bytes
/
LC0450.cpp
File metadata and controls
executable file
·36 lines (31 loc) · 732 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/delete-node-in-a-bst/
Time: O(h)
Space: O(h)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root)
return nullptr;
else if (key != root->val) {
if (key < root->val)
root->left = deleteNode(root->left, key);
else
root->right = deleteNode(root->right, key);
return root;
}
TreeNode *prev = nullptr, *succ = root->right;
while (succ && succ->left)
prev = exchange(succ, succ->left);
if (succ)
succ->left = root->left;
else
succ = root->left;
if (prev)
prev->left = exchange(succ->right, root->right);
delete root;
return succ;
}
};