Skip to content

Commit e88e8c7

Browse files
Add files via upload
1 parent 2e28b95 commit e88e8c7

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Range Sum of BST/Range_Sum_of_BST.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// 使用二叉树中序遍历的解法
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* struct TreeNode {
6+
* int val;
7+
* TreeNode *left;
8+
* TreeNode *right;
9+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10+
* };
11+
*/
12+
class Solution
13+
{
14+
public:
15+
int rangeSumBST(TreeNode* root, int L, int R)
16+
{
17+
stack<TreeNode*> memo;
18+
int res = 0;
19+
while (root || !memo.empty())
20+
{
21+
while (root)
22+
{
23+
memo.push(root);
24+
root = root->left;
25+
}
26+
if (!memo.empty())
27+
{
28+
root = memo.top();
29+
memo.pop();
30+
31+
if (root->val >= L && root->val <= R)
32+
res += root->val;
33+
34+
root = root->right;
35+
}
36+
}
37+
38+
return res;
39+
}
40+
};
41+
42+
43+
// 第二种做法 使用递归
44+
// Runtime: 144 ms, faster than 84.60% of C++ online submissions for Range Sum of BST.
45+
// Memory Usage: 41.2 MB, less than 80.00% of C++ online submissions for Range Sum of BST.
46+
47+
/**
48+
* Definition for a binary tree node.
49+
* struct TreeNode {
50+
* int val;
51+
* TreeNode *left;
52+
* TreeNode *right;
53+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
54+
* };
55+
*/
56+
class Solution
57+
{
58+
public:
59+
int rangeSumBST(TreeNode* root, int L, int R)
60+
{
61+
if (root == nullptr || L > R)
62+
return 0;
63+
else if (L == R && L == root->val)
64+
return root->val;
65+
else if (L > root->val)
66+
return rangeSumBST(root->right, L, R);
67+
else if (root->val > R)
68+
return rangeSumBST(root->left, L, R);
69+
else
70+
return rangeSumBST(root->left, L, root->val - 1) + rangeSumBST(root->right, root->val + 1, R) + root->val;
71+
}
72+
};

0 commit comments

Comments
 (0)