首页 > 其他 > 详细

LintCode "Remove Node in Binary Search Tree"

时间:2015-10-05 06:59:24      阅读:199      评论:0      收藏:0      [点我收藏+]

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

LintCode "Remove Node in Binary Search Tree"

原文:http://www.cnblogs.com/tonix/p/4855294.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!