码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Remove Node in Binary Search Tree

时间:2015-07-09 22:39:36      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

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 

 
 
哎,先来个偷懒的写法吧。分类讨论情况太多了。  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;
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 };

 

[LintCode] Remove Node in Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4634419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!