标签:
http://www.lintcode.com/en/problem/remove-node-in-binary-search-tree/#
Given a root ofBINARY
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 theBINARY
search tree, do nothing. You should keep the tree still aBINARY
search tree after removal.
Example
Given binary search tree:
5
/ \
3 6
/ \
2 4
Remove 3, you can either return:
5
/ \
2 6
\
4
or :
5
/ \
4 6
/
2
先上代码,有时间了再给解析,此题是面试常考题,连微软亚洲研究院都出过该题..
/**
* 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) {
if (root == NULL) {
return root;
}
int dummyValue;
if (value != INT_MIN) {
dummyValue = value + 1;
TreeNode *dummyNode = new TreeNode(dummyValue);
dummyNode->left = root;
return removeNodeHelper(dummyNode, value)->left;
} else {
dummyValue = value - 1;
TreeNode *dummyNode = new TreeNode(dummyValue);
dummyNode->right = root;
return removeNodeHelper(dummyNode, value)->right;
}
}
private:
TreeNode *removeNodeHelper(TreeNode *root, int value) {
if (root == NULL) {
return NULL;
}
if (value < root->val) {
root->left = removeNodeHelper(root->left, value);
} else if (root->val < value) {
root->right = removeNodeHelper(root->right, value);
} else { // while equal, then delete, change the pointer
if (root->left == NULL) {
TreeNode *rightChild = root->right;
delete root;
return rightChild;
}
if (root->right == NULL) {
TreeNode *leftChild = root->left;
delete root;
return leftChild;
}
// left child and right child all exsit
TreeNode *childOfRight = findMinOfRight(root->right);
TreeNode *childOfRightBak = new TreeNode(childOfRight->val);
childOfRightBak->left = root->left;
childOfRightBak->right = root->right;
root->right = removeNodeHelper(root->right, childOfRight->val);
delete root;
return childOfRightBak;
}
return root;
}
TreeNode *findMinOfRight(TreeNode *root) {
if (root->left == NULL) {
return root;
}
return findMinOfRight(root->left);
}
};[LintCode] Remove Node in Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/jianxinzhou/p/4544508.html