Given the
The binary search tree is guaranteed to have unique values.
Example 1:
root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32
Solution in C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int rangeSumBST(TreeNode* root, int L, int R) {
int sum = 0;
return cal_sum(root, L, R, sum);
}
int cal_sum (TreeNode* root, int L, int R, int &sum){
if(!root){
return 0;
}
if(root->left){
cal_sum(root->left, L, R, sum);
}
if(root->right){
cal_sum(root->right, L, R, sum);
}
if(root->val >= L && root->val <= R){
sum += root->val;
}
return sum;
}
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int rangeSumBST(TreeNode* root, int L, int R) {
int sum = 0;
return cal_sum(root, L, R, sum);
}
int cal_sum (TreeNode* root, int L, int R, int &sum){
if(!root){
return 0;
}
if(root->left){
cal_sum(root->left, L, R, sum);
}
if(root->right){
cal_sum(root->right, L, R, sum);
}
if(root->val >= L && root->val <= R){
sum += root->val;
}
return sum;
}
Comments
Post a Comment