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 = 15
Output: 32

Example 2:

Input: root = 10
Output: 23

题意:

LeetCode 938. Range Sum of BST

/**
 * 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 == nullptr) 
            return 0;
        else if (root->val > R)
        {
            return rangeSumBST(root->left, L, R);
        }
        else if (root->val < L)
        {
            return rangeSumBST(root->right, L, R);
        }
        else
        {
            return root->val + rangeSumBST(root->left, L, root->val) + rangeSumBST(root->right, root->val, R);
        }
           
            
    }
};

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2021-07-31
  • 2022-12-23
  • 2022-01-25
猜你喜欢
  • 2021-12-28
  • 2021-12-25
  • 2021-08-07
  • 2021-10-03
  • 2021-12-01
相关资源
相似解决方案