二叉搜索树的范围和

给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。

二叉搜索树保证具有唯一的值。

示例 1:

输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例 2:

输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
 

提示:

树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。

code:中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    void rangeSumBSTCore(TreeNode* root,int L,int R,int& res)
    {
        if(!root)
            return ;

        rangeSumBSTCore(root->left,L,R,res);
        if(root->val>=L&&root->val<=R)
            res+=root->val;
        rangeSumBSTCore(root->right,L,R,res);
    }
public:
    int rangeSumBST(TreeNode* root, int L, int R) {
        if(!root||R<=L)
            return 0;
        
        int res=0;
        rangeSumBSTCore(root,L,R,res);
        return res;
    }
};

 code:不需要遍历完整棵树,中序遍历后可以得到一个升序序列,我们只需要数组中L&R之间的数值,故如果当前节点小于L,则遍历右子树,若果当前结点大于R,则遍历左子树,其他情况遍历左右子树和当前节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int rangeSumBST(TreeNode* root, int L, int R) {
        if(!root||R<=L)
            return 0;
        
        if(root->val<L)
            return rangeSumBST(root->right,L,R);
        else if(root->val>R)
            return rangeSumBST(root->left,L,R);
        else
            return root->val+rangeSumBST(root->left,L,R)+rangeSumBST(root->right,L,R);
    }
};
原文地址:https://www.cnblogs.com/tianzeng/p/12266267.html