-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path0450.cpp
70 lines (67 loc) · 1.7 KB
/
0450.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
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
TreeNode* deleteNode(TreeNode* root, int key)
{
if (root == nullptr) return nullptr;
if (key < root->val)
{
root->left = deleteNode(root->left, key);
return root;
}
else if (key > root->val)
{
root->right = deleteNode(root->right, key);
return root;
}
else
{
if (root->left == nullptr)
{
TreeNode* rootRight = root->right;
delete root;
return rootRight;
}
if (root->right == nullptr)
{
TreeNode* rootLeft = root->left;
delete root;
return rootLeft;
}
TreeNode* tmp = minTreeNode(root->right);
tmp->right = removeMin(root->right);
tmp->left = root->left;
delete root;
return tmp;
}
}
private:
TreeNode* minTreeNode(TreeNode* root)
{
if (root->left == nullptr) return root;
return minTreeNode(root->left);
}
TreeNode* removeMin(TreeNode* root)
{
if (root->left == nullptr)
{
TreeNode* rootRight = root->right;
return rootRight;
}
root->left = removeMin(root->left);
return root;
}
};