题解 | #农场牛的最佳观赏区间# java
农场牛的最佳观赏区间
https://www.nowcoder.com/practice/7b49f5ad9814424d8c41de44f671d59e
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整型 */ public int rangeSumBST (TreeNode root, int low, int high) { // write code here if (root == null) return 0; if (root.val < low) return rangeSumBST(root.right, low, high); if (root.val > high) return rangeSumBST(root.left, low, high); return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high); } }
Java代码
考察的知识点是:计算二叉搜索树中值位于指定范围内的节点值的总和。
代码的文字解释如下:
rangeSumBST
方法接收TreeNode
类型参数,以及两个int
类型的参数low
和high
,并返回一个整型结果。- 在
rangeSumBST
方法中,首先检查root
是否为null
,如果是,则返回0。 - 继续检查
root
的值与low
和high
的大小关系。如果 root 的值小于 low,则递归调用 rangeSumBST 方法传入右子树,同时保持 low 和 high 参数不变,忽略当前节点及其左子树。如果 root 的值大于 high,则递归调用 rangeSumBST 方法传入左子树,同时保持 low 和 high 参数不变,忽略当前节点及其右子树。如果 root 的值在 low 和 high 之间(包含边界),则将 root 的值累加到结果中,并同时递归调用 rangeSumBST 方法传入左子树和右子树,保持相同的 low 和 high 参数。 - 返回计算得到的结果作为方法的返回值。