# Question

Formatted question description: https://leetcode.ca/all/938.html

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

Note:
The number of nodes in the tree is at most 10000.
The final answer is guaranteed to be less than 2^31.



# Algorithm 1

This question gives a binary search tree, and also gives two integers L and R, so that the sum of all node values in the interval [L, R] is returned, that is, to find all the values in this interval For the nodes within, add up all the node values and return. The simplest and rude idea is to traverse all the nodes, check whether the value of each node is in the interval, if it is, add its value, and finally return the accumulated sum, see the code as follows:

# Code 1

C++

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


• 
public class Range_Sum_of_BST {

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {

int sum = 0; // could be long. overflow

public int rangeSumBST(TreeNode root, int L, int R) {

dfs(root, L, R);
return sum;
}

public void dfs(TreeNode node, int L, int R) {

if (node == null) {
return;
}

if (node.val >= L && node.val <= R) {
sum += node.val;
dfs(node.left, L, R);
dfs(node.right, L, R);
}

if (node.val < L) {
dfs(node.right, L, R);
}

if (node.val > R) {
dfs(node.left, L, R);
}
}

}
}


# Algorithm 2

Although the above solution can be passed, it is not the optimal solution, because the nature of the binary search tree is not used. Since BST has the characteristics of left< root< right, pruning can be carried out, if the current node value is less than L , It means that all nodes of the left subtree are less than L, and the left subtree can be cut directly; similarly, if the current node value is greater than R, it means that all nodes of the right subtree are greater than R, and you can directly Cut the right subtree. Otherwise, it means that the current node value is exactly in the interval, add up its value, and call the recursive function on the left and right sub-nodes respectively, see the code as follows:

# Code 2

C++

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

############

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
if (low <= root.val && root.val <= high) {
return root.val + rangeSumBST(root.left, low, high)
+ rangeSumBST(root.right, low, high);
} else if (root.val < low) {
return rangeSumBST(root.right, low, high);
} else {
return rangeSumBST(root.left, low, high);
}
}
}

• // OJ: https://leetcode.com/problems/transpose-matrix/
// Time: O(N)
// Space: O(H)
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if (!root) return 0;
return (root->val >= L && root->val <= R ? root->val : 0) + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
};

• # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
def search(node):
if not node:
return
if low <= node.val <= high:
self.ans += node.val
search(node.left)
search(node.right)
elif node.val < low:
search(node.right)
elif node.val > high:
search(node.left)

self.ans = 0
search(root)
return self.ans

############

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
if not root:
return 0
res = 0
if L <= root.val <= R:
res += root.val
res += self.rangeSumBST(root.left, L, R)
res += self.rangeSumBST(root.right, L, R)
elif root.val < L:
res += self.rangeSumBST(root.right, L, R)
elif root.val > R:
res += self.rangeSumBST(root.left, L, R)
return res

• /**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func rangeSumBST(root *TreeNode, low int, high int) int {
if root == nil {
return 0
}
if low <= root.Val && root.Val <= high {
return root.Val + rangeSumBST(root.Left, low, high) + rangeSumBST(root.Right, low, high)
} else if root.Val < low {
return rangeSumBST(root.Right, low, high)
} else {
return rangeSumBST(root.Left, low, high)
}
}

• /**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
List<Integer> inorderTraversal = inorderTraversal(root);
int leftIndex = inorderTraversal.indexOf(L), rightIndex = inorderTraversal.indexOf(R);
int sum = 0;
for (int i = leftIndex; i <= rightIndex; i++)
sum += inorderTraversal.get(i);
return sum;
}

public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> inorderTraversal = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
TreeNode visitNode = stack.pop();
node = visitNode.right;
}
return inorderTraversal;
}
}

############

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
if (low <= root.val && root.val <= high) {
return root.val + rangeSumBST(root.left, low, high)
+ rangeSumBST(root.right, low, high);
} else if (root.val < low) {
return rangeSumBST(root.right, low, high);
} else {
return rangeSumBST(root.left, low, high);
}
}
}

• // OJ: https://leetcode.com/problems/transpose-matrix/
// Time: O(N)
// Space: O(H)
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if (!root) return 0;
return (root->val >= L && root->val <= R ? root->val : 0) + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
};

• # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
def search(node):
if not node:
return
if low <= node.val <= high:
self.ans += node.val
search(node.left)
search(node.right)
elif node.val < low:
search(node.right)
elif node.val > high:
search(node.left)

self.ans = 0
search(root)
return self.ans

############

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
if not root:
return 0
res = 0
if L <= root.val <= R:
res += root.val
res += self.rangeSumBST(root.left, L, R)
res += self.rangeSumBST(root.right, L, R)
elif root.val < L:
res += self.rangeSumBST(root.right, L, R)
elif root.val > R:
res += self.rangeSumBST(root.left, L, R)
return res

• /**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func rangeSumBST(root *TreeNode, low int, high int) int {
if root == nil {
return 0
}
if low <= root.Val && root.Val <= high {
return root.Val + rangeSumBST(root.Left, low, high) + rangeSumBST(root.Right, low, high)
} else if root.Val < low {
return rangeSumBST(root.Right, low, high)
} else {
return rangeSumBST(root.Left, low, high)
}
}