原题
https://leetcode-cn.com/problems/range-sum-of-bst/
思路
二叉搜索树BST的中序遍历是升序的,故可以升序到high
后直接return
题解
/**
* 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 {
int res = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
if (root != null) {
midOrder(root, low, high);
}
return res;
}
private void midOrder(TreeNode node, int low, int high){
if (node.left != null) {
midOrder(node.left, low, high);
}
int val = node.val;
if (val > high) {
return;
}
if (low <= val) {
res += val;
}
if (node.right != null) {
midOrder(node.right, low, high);
}
}
}