题目来源
删除二叉搜索树的一个节点。
题目确实不难,不过我写的有点乱,而且一开始没有考虑那么多东西,错了好多次才AC的,应该是有简洁一点的方法的。
我的代码如下:
/**
* 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 *pre = NULL, *cur = root;
while (cur != NULL) {
if (cur->val == key) {
if (cur->left == NULL) {
if (pre == NULL) {
delete cur;
return cur->right;
}
else {
if (pre->val > cur->val)
pre->left = cur->right;
else
pre->right = cur->right;
delete cur;
return root;
}
}
else {
if (cur->right == NULL) {
if (pre == NULL) {
delete cur;
return cur->left;
}
else {
if (pre->val > cur->val)
pre->left = cur->left;
else
pre->right = cur->left;
delete cur;
return root;
}
}
TreeNode *left_max = cur->left;
while (left_max->right)
left_max = left_max->right;
left_max->right = cur->right->left;
cur->right->left = cur->left;
if (pre == NULL) {
delete cur;
return cur->right;
}
else {
if (pre->val > cur->val)
pre->left = cur->right;
else
pre->right = cur->right;
delete cur;
return root;
}
}
}
else if (cur->val > key) {
pre = cur;
cur = cur->left;
}
else {
pre = cur;
cur = cur->right;
}
}
return root;
}
};
看了看讨论区,可以用简洁一点的递归的方法来实现,代码如下:
/**
* 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 == NULL)
return root;
if (key > root->val)
root->right = deleteNode(root->right, key);
else if (key < root->val)
root->left = deleteNode(root->left, key);
else {
if (root->left == NULL)
return root->right;
else if (root->right == NULL)
return root->left;
root->val = findmin(root->right)->val;
root->right = deleteNode(root->right, root->val);
}
return root;
}
private:
TreeNode *findmin(TreeNode *node)
{
while (node->left)
node = node->left;
return node;
}
};