Skip to content

Commit c290f14

Browse files
authored
Create Range Sum of BST.java
1 parent bcb83ef commit c290f14

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Easy/Range Sum of BST.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public int rangeSumBST(TreeNode root, int low, int high) {
18+
int[] rangeSum = {0};
19+
helper(root, low, high, rangeSum);
20+
return rangeSum[0];
21+
}
22+
23+
private void helper(TreeNode root, int low, int high, int[] rangeSum) {
24+
if (root == null) {
25+
return;
26+
}
27+
if (root.val >= low && root.val <= high) {
28+
rangeSum[0] += root.val;
29+
}
30+
if (root.val >= low) {
31+
helper(root.left, low, high, rangeSum);
32+
}
33+
if (root.val <= high) {
34+
helper(root.right, low, high, rangeSum);
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)