给定一棵具有不同节点值的二叉查找树,删除树中与给定值相同的节点。如果树中没有相同值的节点,就不做任何处理。你应该保证处理之后的树仍是二叉查找树。
样例
给出如下二叉查找树:
5
/ \
3 6
/ \
2 4
删除节点3之后,你可以返回:
5
/ \
2 6
\
4
或者:
5
/ \
4 6
/
2
题目链接:http://www.lintcode.com/zh-cn/problem/remove-node-in-binary-search-tree/
先通过递归找到要删除节点的位置,然后找到要删除节点的右子树中最小的点,将它赋值给要删除的节点,然后删除节点。
/**
* 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 root;
if (root->val > value) root->left = removeNode(root->left,value);
else if (root->val < value) root->right = removeNode(root->right,value);
else if (root->left && root->right) {
root->val = findMin(root->right);
removeNode(root->right,root->val);
}
else root = (root->left) ? root->left : root->right;
return root;
}
int findMin(TreeNode *root) {
while (root->left) root = root->left;
return root->val;
}
};