Range Sum of BST Solutions in C++
Number 938
Difficulty Easy
Acceptance 81.4%
Link LeetCode
Other languages —
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/range-sum-of-bst//// Author : liuyubobobo/// Time : 2018-11-10#include <iostream>using namespace std;/// Recursion/// Time Complexity: O(n)/// Space Complexity: O(h)/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:int rangeSumBST(TreeNode* root, int L, int R) {return sum(root, L, R);}private:int sum(TreeNode* node, int L, int R){if(!node)return 0;if(node->val < L)return sum(node->right, L, R);if(node->val > R)return sum(node->left, L, R);int res = node->val;res += sum(node->left, L, node->val - 1);res += sum(node->right, node->val + 1, R);return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/range-sum-of-bst//// Author : liuyubobobo/// Time : 2018-11-11#include <iostream>#include <stack>using namespace std;/// Non-Recursion, using stack/// Time Complexity: O(n)/// Space Complexity: O(h)/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:int rangeSumBST(TreeNode* root, int L, int R) {int res = 0;stack<TreeNode*> stack;stack.push(root);while(!stack.empty()){TreeNode* cur = stack.top();stack.pop();if(!cur) continue;if(L <= cur->val && cur->val <= R){res += cur->val;stack.push(cur->right);stack.push(cur->left);}else if(cur->val < L)stack.push(cur->right);elsestack.push(cur->left);}return res;}};int main() {return 0;}