Problem:
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.
Explanation:
在搜索二叉树中计算在某一范围之间的数字之和。
My Thinking:
遍历累加即可,利用搜索二叉树减少递归次数。
My Solution:
class Solution {
private int sum=0;
public int rangeSumBST(TreeNode root, int L, int R) {
if(root==null)
return sum;
if(root.val>=L && root.val<=R)//防止根结点就不在范围里
sum+=root.val;
if(root.val!=L)
rangeSumBST(root.left,L,R);
if(root.val!=R)
rangeSumBST(root.right,L,R);
return sum;
}
}
Optimum Thinking:
Optimum Solution: