题解 | #农场牛的最佳观赏区间#
农场牛的最佳观赏区间
https://www.nowcoder.com/practice/7b49f5ad9814424d8c41de44f671d59e
考察二叉树遍历的应用。其实就是对于给定的区间遍历节点,在内部的求和就可以了
完整Java代码如下所示
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 {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param low int整型
* @param high int整型
* @return int整型
*/
ArrayList<Integer> list = new ArrayList<>();
public int rangeSumBST (TreeNode root, int low, int high) {
// write code here
int res = 0;
if(root==null) return res;
dfs(root);
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(num>=low && num<=high) res+=num;
}
return res;
}
public void dfs(TreeNode root){
if(root==null) return;
dfs(root.left);
list.add(root.val);
dfs(root.right);
}
}

查看21道真题和解析