标签:out issue analysis guarantee final mil problem 代码 tco
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
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
10000
.2^31
.解法一:
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
int res = 0;
helper(root, L, R, res);
return res;
}
void helper(TreeNode* node, int L, int R, int& res) {
if (!node) return;
if (node->val >= L && node->val <= R) res += node->val;
helper(node->left, L, R, res);
helper(node->right, L, R, res);
}
};
解法二:
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if (!root) return 0;
if (root->val < L) return rangeSumBST(root->right, L, R);
if (root->val > R) return rangeSumBST(root->left, L, R);
return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
};
https://github.com/grandyang/leetcode/issues/938
https://leetcode.com/problems/range-sum-of-bst/
https://leetcode.com/problems/range-sum-of-bst/discuss/205181/Java-4-lines-Beats-100
[LeetCode] 938. Range Sum of BST 二叉搜索树的区间和
标签:out issue analysis guarantee final mil problem 代码 tco
原文地址:https://www.cnblogs.com/grandyang/p/12640445.html