-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path450.cpp
More file actions
81 lines (69 loc) · 1.67 KB
/
Copy path450.cpp
File metadata and controls
81 lines (69 loc) · 1.67 KB
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
class Solution {
public:
//不用真删除节点迁移指针,换值就行了
//返回值表示刚刚递归的节点是不是叶子节点
void del(TreeNode* p, TreeNode* parent)
{
if(!p->left && !p->right)
{
if(parent->left == p)
{
parent->left = NULL;
}
else
{
parent->right = NULL;
}
}
TreeNode* n;
TreeNode* np;
if(p->left)
{
n = p->left;
np = p;
while(n->right)
{
np = n;
n = n->right;
}
p->val = n->val;
del(n, np);
}
else if(p->right)
{
n = p->right;
np = p;
while(n->left)
{
np = n;
n = n->left;
}
p->val = n->val;
del(n, np);
}
}
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode* p = root;
TreeNode* parent;
int direct = 0;
if(!p)return root;
while(p)
{
if(p->val == key)break;
if(key < p->val)
{
parent = p;
p = p->left;
}
else if(key > p->val)
{
parent = p;
p = p->right;
}
}
if(!p)return root;
if(p == root && !p->left && !p->right)return NULL;
del(p, parent);
return root;
}
};