原文链接 [链接] Description: Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary sea ..

[每日 LeetCode] 938. Range Sum of BST

原文链接 [每日 LeetCode] 938. Range Sum of BST

Description:

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).

The binary search tree is guaranteed to have unique values.

Example 1:

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23

思路:本题题意为:找出一个 BST 中,计算在 [L,R] 双闭区间内的所有节点的值的和。依旧使用递归思想,递归基本条件是 root 为空,返回 sum。另外分三种情况考虑。


C++ 代码

/**
 * 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) {
        return helper(root,L,R,0);
    } 
    int helper(TreeNode* node,int L,int R,int sum){
        if(node==NULL)
            return sum;
        int curr = node->val;
        if(curr<L)
            return helper(node->right,L,R,sum);
        else if(curr>R)
            return helper(node->left,L,R,sum);
        else
            return helper(node->left,L,R,sum)+helper(node->right,L,R,sum)+curr;
    }
};

运行时间:140ms

运行内存:41.2M

  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    154 引用 • 36 回帖
  • Tree
    33 引用 • 5 回帖
  • Easy
    101 引用 • 10 回帖
回帖   
请输入回帖内容...