给定一个有根的二分搜索树和两个数字min和max,修整这个树使得所有的数字在这个新的树种都是在min和max之间(包括min和max)。然后这个所得的树仍然是合法的二分搜索树。举个例子,输入是:
然后我们给定min为5和max为13,这样得到的二分搜索树的结果应该是:
样例
样例1
输入:
{8,3,10,1,6,#,14,#,#,4,7,13}
5
13
输出: {8, 6, 10, #, 7, #, 13}
说明:树的图片在题面描述里已经给出
样例2
输入:
{1,0,2}
1
2
输出: {1,#,2}
说明:
输入是
1
/ \
0 2
输出是
1
\
2
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: given BST
* @param minimum: the lower limit
* @param maximum: the upper limit
* @return: the root of the new tree
*/
TreeNode* ret;
TreeNode * trimBST(TreeNode * root, int L, int R) {
// write your code here
if(root == NULL)
return root;
ret = NULL;
bianli(root, L, R);
return ret;
}
void bianli(TreeNode* root, int L, int R)
{
if(root != NULL)
{
if(root->val >= L && root->val <= R)
{
ret = insertIntoBST(ret, root->val);
}
bianli(root->left,L, R);
bianli(root->right,L, R);
}
}
TreeNode* insertIntoBST(TreeNode* root, int val)
{
if(root == NULL)
return new TreeNode(val);
if(val < root->val) //说明要插入左边
{
TreeNode* left = insertIntoBST(root->left,val);
root->left = left;
}
else if(val > root->val)
{
TreeNode* right = insertIntoBST(root->right,val);
root->right = right;
}
return root;
}
};