938. 二叉搜索树的范围和
思路一: 暴力DFS
class Solution {
int sum = 0;
public void dfs(TreeNode root,int low, int high){
if(root == null)
return;
dfs(root.left,low,high);
if(low<=root.val && root.val <=high){
sum+=root.val;
}
dfs(root.right,low,high);
}
public int rangeSumBST(TreeNode root, int low, int high) {
dfs(root,low,high);
return sum;
}
}
思路二:递归
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
if(root == null)
return 0;
if(root.val>high)
return rangeSumBST(root.left,low,high);
if(root.val<low)
return rangeSumBST(root.right,low,high);
else
return root.val+rangeSumBST(root.left,low,high)+rangeSumBST(root.right,low,high);
}
}