题目描述:
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
https://leetcode-cn.com/problems/range-sum-of-bst/
解题思路:
二叉搜索树是按照中序遍历,root = [10,5,15,3,7,null,18], low = 7, high = 15,中序遍历结果是3,5,7,10,15,18,从7到15,即为7+10+15=32,所以关键是得到中序遍历的结果,我通过深搜,将遍历结果放在result里,再对result进行遍历,将区间内的数加起来,这样做时间复杂度和空间复杂度都很高,555555
c++代码:
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
vector<int> result;
int re=0;
dfs(root,result);
for(int i=0,j=result.size()-1;i<=j;){
if(result[i]!=low) i++;
if(result[j]!=high) j--;
if(result[i]==low&&result[j]==high){
for(int t=i;t<=j;t++){
re+=result[t];
}
break;
}
}
return re;
}
void dfs(TreeNode* root,vector<int>& result){
if(root==nullptr) return;
dfs(root->left,result);
result.push_back(root->val);
dfs(root->right,result);
}
};