zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    两小时后执行打开浏览器的操作
    Markdown语法
    Python机器学习2.2
    身份证姓名与身份证号校验
    根据银行卡号获取开户行
    生成微信小程序二维码
    .net 生成二维码
    微信支付API V3(.Net Core)
    .net 生成项目xml描述文件
    汉字排序问题
  • 原文地址:https://www.cnblogs.com/tonix/p/4855294.html
Copyright © 2011-2022 走看看