修剪二叉搜索树

给定一个有根的二分搜索树和两个数字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;   
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值