Remove Node in Binary Search Tree
Given a root of Binary Search Tree with the unique value for each node. Remove the node with given value. If There is no such a node with given value in the binary search tree, does nothing. You should keep the tree still a binary search tree after removal.
Example
Given Binary search tree:
5
/ \
3 6
/ \
2 4
Remove 3, you can either return:
5
/ \
2 6
\
4
Or:
5
/ \
4 6
/
2
Tags Expand
Lintcode Copyright Binary Search Tree Ah, first to a lazy writing it. There are too many categories of discussions. T. T
1 /**2 * Definition of TreeNode:3 * Class TreeNode {4 * Public:5 * int val;6 * TreeNode *left, *right;7 * TreeNode (int val) {8 * This->val = val;9 * This->left = This->right = NULL;Ten * } One * } A */ - classSolution { - Public: the /** - * @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* Buildtree (vector<treenode*> &v,intLeftintRight ) { + if(Left > right)returnNULL; A intMid = left + ((right-left) >>1); atV[mid]->left = Buildtree (V, left, mid-1); -V[mid]->right = Buildtree (V, mid +1, right); - returnV[mid]; - } -Treenode* RemoveNode (treenode* root,intvalue) { - //Write your code here inVector<treenode*>v; -TreeNode *cur = root, *tmp; toStack<treenode*>Stk; + while(cur! = NULL | |!Stk.empty ()) { - if(cur! =NULL) { the Stk.push (cur); *Cur = cur->Left ; $}Else {Panax NotoginsengCur =stk.top (); - Stk.pop (); theTMP =cur; +Cur = cur->Right ; A if(Tmp->val! =value) { the V.push_back (TMP); +}Else { - Deletetmp; $TMP =NULL; $ } - } - } the returnBuildtree (V,0, (int) V.size ()-1); - }Wuyi};
[Lintcode] Remove Node in Binary Search Tree