-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path450. Delete Node in a BST.cpp
90 lines (83 loc) · 2.2 KB
/
450. Delete Node in a 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode* head = new TreeNode(0);
head->left = root;
dfs(head, root, key);
return head->left;
}
void dfs(TreeNode* pre, TreeNode* cur, int key){
if(!cur) return;
cur->val > key ? dfs(cur, cur->left, key) : cur->val < key ? dfs(cur, cur->right, key) : helper(pre, cur);
}
void helper(TreeNode* pre, TreeNode* cur){
TreeNode* p = cur->left;
while(p && p->right) p = p->right;
p ? p->right = cur->right : cur->left = cur->right;
cur == pre->left ? pre->left = cur->left : pre->right = cur->left;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) {
return NULL;
}
TreeNode* head = new TreeNode(0);
head->left = root;
TreeNode* parent;
TreeNode* node = dfs(root, head, key, parent);
if (!node) {
return root;
}
TreeNode* l = node->left;
TreeNode* r = node->right;
TreeNode* p = r;
while (p && p->left) {
p = p->left;
}
if (!r) {
r = l;
} else if (p) {
p->left = l;
}
if (node == parent->left) {
parent->left = r;
} else {
parent->right = r;
}
return head->left;
}
TreeNode* dfs(TreeNode* cur, TreeNode* pre, int key, TreeNode*& parent) {
if (!cur) {
return NULL;
}
if (cur->val == key) {
parent = pre;
return cur;
}
if (cur->val > key) {
return dfs(cur->left, cur, key, parent);
} else {
return dfs(cur->right, cur, key, parent);
}
}
};