LintCode 87: Remove Node in Binary Search Tree BST操作经典题

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值