LintCode "Remove Node in Binary Search Tree"

Not hard to find a solution, but there are several corner cases.

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) {
        //    Find it
        TreeNode *p = root, *pp = nullptr;
        bool bLeft = false;
        while(p)
        {
            if(p->val == value)
            {
                break;
            }
            pp = p;
            if(p->val < value)
            {
                p = p->right;
            }
            else if(p->val > value)
            {
                p = p->left;
            }
            bLeft = pp->left == p;
        }
        if(!p) return root;

        //    Case 1: no children
        if(!p->left && !p->right)
        {
            if (!pp) return nullptr;
            
            if(bLeft)
                pp->left = nullptr;
            else
                pp->right= nullptr;
            return root;
        }

        //    Compose new left sub-tree
        TreeNode *pl = p->left, *pr = p->right, *pNewSubRoot = nullptr;
        //    Case 2: has both children
        if (pl && pr)
        {
            TreeNode *p0 = pl, *pp0 = pl;
            while(p0->right)
            {
                pp0 = p0;
                p0 = p0->right;
            }
            if(pp0 != p0)
            {
                pp0->right = p0->left;
                p0->left = pl;
            }
            p0->right = pr;

            pNewSubRoot = p0;
        }
        //    Case 3: only 1 child
        else
        {
            TreeNode *pc = pl ? pl : pr;
            if (!pp) return pc;
            if(bLeft)
                pp->left = pc;
            else
                pp->right= pc;
        }

        //    Return
        if(!pp)
        {
            return pNewSubRoot;
        }

        return root;
    }
};
View Code

转载于:https://www.cnblogs.com/tonix/p/4855294.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值