题目考察的知识点
二叉树遍历操作以及对于线索二叉树中序遍历得到升序序列的理解
题目解答方法的文字分析
可以中序遍历完线索二叉树(哪种遍历方式其实无所谓),将值存储在集合中,对于集合中的值进行统计,满足区间要求的进行累加求和即可。
本题解析所用的编程语言
使用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); } }