Lintcode "Remove Node in Binary Search Tree"

Source: Internet
Author: User
Tags lintcode

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

classSolution { 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,intvalue) {        //Find ItTreeNode *p = root, *pp =nullptr; BOOLBleft =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)returnRoot; //Case 1:no Children        if(!p->left &&!p->Right ) {            if(!PP)returnnullptr; if(bleft) pp->left =nullptr; Elsepp->right=nullptr; returnRoot; }        //Compose New Left sub-treeTreeNode *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)returnpc; if(bleft) pp->left =pc; Elsepp->right=pc; }        //Return        if(!PP) {            returnPnewsubroot; }        returnRoot; }};
View Code

Lintcode "Remove Node in Binary Search Tree"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.