利用bst的特性做,如果当前结点符合,就让sum加上当前的,并递归左右。如果当前小于low,就去右边就行了,否则就去左边。最后返回sum。
一开始考虑中序遍历,很明显这样很快,O(logn),中序就是O(n)了
class Solution {
public:
void dfs(TreeNode* root, int low ,int high){
if(root == nullptr) return;
//根据low和high和val递归左边or右边
if(root->val >= low && root->val <= high){
sum += root->val;
dfs(root->left,low,high);
dfs(root->right,low,high);
}
else if(root->val < low){
dfs(root->right,low,high);
}
else{
dfs(root->left,low,high);
}
}
int rangeSumBST(TreeNode* root, int low, int high) {
//bst,碰到大于high的就停止
dfs(root,low,high);
return sum;
}
private:
int sum = 0;
};
碰到大于high就返回,但是没搞懂,为什么不能在上面就判断?后面搞懂了,因为比如一开始根结点是100,左节点是10,那么你在最开始就退出了,当然错了!!要在根操作那里进行判断
class Solution {
public:
void dfs(TreeNode* root, int low ,int high){
if(root == nullptr) return;
//当前值超过了就直接return
dfs(root->left,low,high);
if(root->val > high) return;
if(root->val >= low) sum += root->val;
dfs(root->right,low,high);
}
int rangeSumBST(TreeNode* root, int low, int high) {
//bst,碰到大于high的就停止
dfs(root,low,high);
return sum;
}
private:
int sum = 0;
};