87-刪除二叉查找樹的節點
給定一棵具有不同節點值的二叉查找樹,刪除樹中與給定值相同的節點。如果樹中沒有相同值的節點,就不做任何處理。你應該保證處理之后的樹仍是二叉查找樹。
樣例
給出如下二叉查找樹:
刪除節點3之后,你可以返回:
或者:
標簽
二叉查找樹 LintCode 版權所有
思路
若要刪除一個BST的一個結點,需要考慮如下三種情況:
- 需要刪除的節點下並沒有其他子節點
- 需要刪除的節點下有一個子節點(左或右)
- 需要刪除的節點下有兩個子節點(既左右節點都存在)
對這三種情況分別采取的措施是:
- 直接刪除此結點
- 刪除此結點,將此結點父節點連接到此結點左(右)子樹
- 找出此結點右子樹中的最小結點,用以代替要刪除的結點,然后刪除此最小結點
code
/**
* 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);
}
else if(root->val < value) {
root->right = removeNode(root->right, value);
}
else {
if (root->left == NULL || root->right == NULL) {
root = (root->left != NULL) ? root->left : root->right;
}
else {
TreeNode *cur = root->right;
while (cur->left != NULL) {
cur = cur->left;
}
root->val = cur->val;
root->right = removeNode(root->right, cur->val);
}
}
return root;
}
};