美文网首页
LeetCode-938. 二叉搜索树的范围和

LeetCode-938. 二叉搜索树的范围和

作者: 一只可爱的柠檬树 | 来源:发表于2019-06-08 11:30 被阅读0次

题目描述 二叉搜索树的范围和

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

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

示例

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

解题思路

  • 递归,中序遍历二叉树,节点值x满足L<=x<=R条件就加上当前节点的值
  • 注意二叉搜索树的性质,中序遍历即是数字从小到大

代码

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

相关文章

网友评论

      本文标题:LeetCode-938. 二叉搜索树的范围和

      本文链接:https://www.haomeiwen.com/subject/rgbgxctx.html