题目描述:给定二叉搜索树的根结点 root
,返回值位于范围 [low, high]
之间的所有结点的值的和。
示例1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15 输出:32
示例2:
输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 输出:23
思路代码如下所示:
/**
* 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 {
public int rangeSumBST(TreeNode root, int low, int high) {
List<Integer> list = new ArrayList<Integer>();
infixOrder(root,list);
return he(root,low,high,list);
}
public int he(TreeNode root,int low,int high,List<Integer> list){
int temp = 0;//记录范围和
//循环遍历list集合
for(int i=0;i < list.size();i++){
//如果遍历出来的值在范围内,则相加
if(list.get(i) >= low && list.get(i) <= high){
temp = temp + list.get(i);
}
}
return temp;
}
//中序遍历,将遍历结果存入list
public void infixOrder(TreeNode root,List<Integer> list){
if(root == null){
return;
}
infixOrder(root.left,list);
list.add(root.val);
infixOrder(root.right,list);
}
}