[LintCode] Remove Node in Binary Search Tree
Remove Node in Binary Search Tree
Given a root of Binary Search Tree with 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, do 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
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; 10 * } 11 * } 12 */ 13 class Solution { 14 public: 15 /** 16 * @param root: The root of the binary search tree. 17 * @param value: Remove the node with given value. 18 * @return: The root of the binary search tree after removal. 19 */ 20 TreeNode* buildTree(vector<TreeNode*> &v, int left, int right) { 21 if (left > right) return NULL; 22 int mid = left + ((right - left) >> 1); 23 v[mid]->left = buildTree(v, left, mid - 1); 24 v[mid]->right = buildTree(v, mid + 1, right); 25 return v[mid]; 26 } 27 TreeNode* removeNode(TreeNode* root, int value) { 28 // write your code here 29 vector<TreeNode*> v; 30 TreeNode *cur = root, *tmp; 31 stack<TreeNode*> stk; 32 while (cur != NULL || !stk.empty()) { 33 if (cur != NULL) { 34 stk.push(cur); 35 cur = cur->left; 36 } else { 37 cur = stk.top(); 38 stk.pop(); 39 tmp = cur; 40 cur = cur->right; 41 if (tmp->val != value) { 42 v.push_back(tmp); 43 } else { 44 delete tmp; 45 tmp = NULL; 46 } 47 } 48 } 49 return buildTree(v, 0, (int)v.size() - 1); 50 } 51 };