1.题目
2.初解题思路(JAVA语言)
其实就是二叉树的先序遍历+限制条件
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
if(root==null){
return 0;
}
int cnt = 0;
cnt += rangeSumBST(root.left,L,R);
cnt += rangeSumBST(root.right,L,R);
if(root.val>=L&&root.val<=R){
return root.val+cnt;
}
return cnt;
}
}
时间复杂度: T(N),空间复杂度O(N)
3.优化思路
注意到是二叉搜索树,也就是左结点的值一定小于根节点的值,右结点的值一定大于根节点的值,当根节点的值小于 L 的时候, 我们只需要对根节点的右子树进行遍历,当根节点的值大于R的时候,只需要对根节点的左子树进行遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
if(root==null){
return 0;
}
if(root.val<L){
return rangeSumBST(root.right,L,R);
}
if(root.val>R){
return rangeSumBST(root.left,L,R);
}
int cnt = 0;
cnt += rangeSumBST(root.left,L,R);
cnt += rangeSumBST(root.right,L,R);
if(root.val>=L&&root.val<=R){
return root.val+cnt;
}
return cnt;
}
}
时间复杂度: T(N),空间复杂度O(N)
其他思路
还有一种思路是比较特别的, 二叉搜索树的中序遍历是有序的,我们可以直接中序遍历根节点,然后把符合条件的点放入一个List,最后直接遍历List返回结果就可以
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<Integer>();
public int rangeSumBST(TreeNode root, int L, int R) {
getNodes(root,L,R);
return getListSum(list);
}
public void getNodes(TreeNode root, int L, int R){
if(root!=null){
getNodes(root.left,L,R);
if(root.val>=L && root.val<=R){
list.add(root.val);
}
getNodes(root.right,L,R);
}
}
public int getListSum(List<Integer> list){
int cnt = 0;
for(Integer num:list){
cnt+=num.intValue();
}
return cnt;
}
}
时间复杂度: T(N),空间复杂度O(N),但是这种思路在一定程度上减小了内存的开销