码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Remove Node in Binary Search Tree"

时间:2015-10-05 07:02:21      阅读:259      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!