aboutsummaryrefslogtreecommitdiff
path: root/range_sum_bst.c
blob: 9db0643fbca6c5f3a4810d88ec882dd4d2a89fa1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 938. Range Sum of BST
#include "leetcode.h"

/*
 * given the 'root' of a binary search tree and two integers 'low' and 'high',
 * return the sum of values of all nodes with a value in the inclusive range
 * '(low, high)'
 */

struct TreeNode {
  int val;
  struct TreeNode *left;
  struct TreeNode *right;
};

int rangeSumBST(struct TreeNode *root, int low, int high) {
  if (!root)
    return 0;
  else if (root->val >= low && root->val <= high)
    return root->val + rangeSumBST(root->left, low, high) +
           rangeSumBST(root->right, low, high);
  else
    return rangeSumBST(root->left, low, high) +
           rangeSumBST(root->right, low, high);
}