87 · Remove Node in Binary Search Tree
Algorithms
Hard
Accepted Rate
32%
Description
Solution
Notes
Discuss
Leaderboard
Record
Description
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.
Contact me on wechat to get Amazon、Google requent Interview questions . (wechat id : jiuzhang0607)
Example
Example 1:
Input:
Tree = {5,3,6,2,4}
value = 3
Output:
{5,2,6,#,4} or {5,4,6,2}
Explanation:
Given binary search tree:
5
/
3 6
/
2 4
Remove 3, you can either return:
5
/
2 6
4
or
5
/
4 6
/
2
Example 2:
Input:
Tree = {5,3,6,2,4}
value = 4
Output:
{5,3,6,2}
Explanation:
Given binary search tree:
5
/
3 6
/
2 4
Remove 4, you should return:
5
/
3 6
/
2
解法1:先找到要删除的节点,然后分0个子孩子,1个子孩子,2个子孩子3种情况讨论。注意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) return NULL;
if (value < root->val) root->left = removeNode(root->left, value);
else if (value > root->val) root->right = removeNode(root->right, value);
else {
//case 1: 0 child
if (!root->left && !root->right) return NULL;
//case 2: 1 child
if (!root->left && root->right) {
TreeNode *tmp = root->right;
delete root;
return tmp;
}
if (!root->right && root->left) {
TreeNode *tmp = root->left;
delete root;
return tmp;
}
//case 3: 2 children
//find prevNode
//option 1: 找左子树最大值
//TreeNode* node = root->left;
//while (node->right) node = node->right;
//root->val = node->val;
//root->left = removeNode(root->left, node->val);
//option 2:找右子树最小值
TreeNode* node = root->right;
while (node->left) node = node->left;
root->val = node->val;
root->right = removeNode(root->right, node->val);
}
return root;
}
};