LintCode 701. Trim a Binary Search Tree (删减BST树)

  1. Trim a Binary Search Tree
    中文English
    Given the root of a binary search tree and 2 numbers min and max, trim the tree such that all the numbers in the new tree are between min and max (inclusive). The resulting tree should still be a valid binary search tree. So, if we get this tree as input:
    http://www.ardendertat.com/wp-content/uploads/2012/01/bst.png
    and we’re given min value as 5 and max value as 13, then the resulting binary search tree should be:
    http://www.ardendertat.com/wp-content/uploads/2012/01/bst_trim.png

Example
Example1

Input:
{8,3,10,1,6,#,14,#,#,4,7,13}
5
13
Output: {8, 6, 10, #, 7, #, 13}
Explanation:
The picture of tree is in the description.
Example2

Input:
{1,0,2}
1
2
Output: {1,#,2}
Explanation:
Input is
1
/
0 2
Output is
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 * trimBST(TreeNode * root, int minimum, int maximum) {
        if (!root || minimum > maximum) return NULL;
        
        TreeNode * newRoot;
        
        if (root->val < minimum) {
            return trimBST(root->right, minimum, maximum);
        } else if (root->val > maximum) {
            return trimBST(root->left, minimum, maximum);
        } else {
            root->left = trimBST(root->left, minimum, maximum);
            root->right = trimBST(root->right, minimum, maximum);
        }
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值