题目:点这里
解法:
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
int v=0;
if(root==NULL){
return 0;
}
if(root->val>=low&&root->val<=high){
v = root->val;
}
return v+rangeSumBST(root->left,low,high)+rangeSumBST(root->right,low,high);
}
};
正确的做法应该是,找到符合条件的,就加起来继续往下找,
递归的本质就是:当前节点的贡献+左子树的贡献+右子树的贡献,三者缺一不可。
错误解法:
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if(root==nullptr){
return 0;
}
if(root->val>=low&&root->val<=high){
return root->val;
}
return rangeSumBST(root->left,low,high)+rangeSumBST(root->right,low,high);
}
};
我的错误代码思路就是在左子树里面找到符合要求的值,然后在右子树里面找到符合要求的值,最后把他们加起来,但这个题目的思路应该是依此判断根节点左子树右子树,最后把他们三者加起来。其实我后来醒悟过来了,但是我在做的时候一直想不到应该怎么去改变我的代码去实现对应的功能。
反思
根据题目的要求的特定思路,建立适宜的代码,要求返回加和的这种,就需要在递归过程中返回加和的结果。