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"