LintCode Remove Node in Binary Search Tree
Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.
以后估计不会再写了
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
TreeNode* removeNode(TreeNode* root, int value) {
// write your code here
if (root == NULL) {
return NULL;
}
if (root->val > value) {
root->left = removeNode(root->left, value);
return root;
} else if (root->val < value) {
root->right= removeNode(root->right, value);
return root;
}
if (root->left == NULL && root->right == NULL) {
delete root;
return NULL;
}
if (root->left == NULL || root->right == NULL) {
TreeNode* child = root->left ? root->left : root->right;
root->left = child->left;
root->right = child->right;
root->val = child->val;
delete child;
return root;
}
TreeNode* min2move = findMin(root->right);
root->val = min2move->val;
root->right = removeNode(root->right, min2move->val);
return root;
}
TreeNode* findMin(TreeNode* root) {
TreeNode* curr = root;
TreeNode* prev = NULL;
while (curr != NULL) {
prev = curr;
curr = curr->left;
}
return prev;
}
};