aboutsummaryrefslogtreecommitdiff
path: root/range_sum_bst.cpp
blob: 046aee297e4330d740660a2f7fe835af4e52975f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "leetcode.h"

class Solution {
public:
  int rangeSumBST(TreeNode *root, int low, int high) {
    queue<TreeNode *> q;
    q.push(root);
    int sum = 0, v;
    while (q.size()) {
      root = q.front();
      q.pop();
      v = root->val;
      if (v >= low && v <= high)
        sum += v;
      if (v > low && root->left)
        q.push(root->left);
      if (v < high && root->right)
        q.push(root->right);
    }
    return sum;
  }
};