题解 | #农场牛的最佳观赏区间#
农场牛的最佳观赏区间
https://www.nowcoder.com/practice/7b49f5ad9814424d8c41de44f671d59e
思路:中序遍历的结果中,找到第一个大于等于 low 的值,向后依次相加,直到当前的元素的值等于 high 返回 sum 即可。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
List<Integer> list = new ArrayList<>();
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param low int整型
* @param high int整型
* @return int整型
*/
public int rangeSumBST (TreeNode root, int low, int high) {
inOrder(root);
int sum = 0;
int index = 0;
while(index < list.size() && list.get(index) < low) index++;
while(index < list.size() && list.get(index) <= high) sum += list.get(index++);
return sum;
}
void inOrder(TreeNode root){
if(root == null) return;
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
}
查看1道真题和解析
