-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRangeSumOfBST.java
More file actions
44 lines (34 loc) · 1.13 KB
/
RangeSumOfBST.java
File metadata and controls
44 lines (34 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package binary_search_tree;
/**
* Description: https://leetcode.com/problems/range-sum-of-bst
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(h)
*/
public class RangeSumOfBST {
public int rangeSumBSTWithExtraVariable(TreeNode root, int low, int high) {
if (root == null) return 0;
int sum = 0;
if (root.val > low) {
sum += rangeSumBST(root.left, low, high);
}
if (root.val >= low && root.val <= high) {
sum += root.val;
}
if (root.val < high) {
sum += rangeSumBST(root.right, low, high);
}
return sum;
}
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) return 0;
if (root.val < low) return rangeSumBST(root.right, low, high); // traverse right branch
if (root.val > high) return rangeSumBST(root.left, low, high); // traverse left branch
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}