-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ938RangeSumOfSBST.java
More file actions
49 lines (45 loc) · 1.42 KB
/
Q938RangeSumOfSBST.java
File metadata and controls
49 lines (45 loc) · 1.42 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
45
46
47
48
49
/*
@b-knd (jingru) on 06 August 2022 10:26:00
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int sum = 0, low, high;
public int rangeSumBST(TreeNode root, int low, int high) {
this.low = low;
this.high = high;
inorder(root);
return sum;
}
public void inorder(TreeNode root){
if(root != null){
//if root value already smaller/equal to lower limit, we do not need to travel left node as all remaining will be out of range
if(root.val > low){
inorder(root.left);
}
//update sum if value falls in range
if(root.val >= low && root.val <= high){
sum += root.val;
}
//if root value larget/equal to upper limit, do not need to travel right nodes (def out of range)
if(root.val < high){
inorder(root.right);
}
}
}
}
//Runtime: 0 ms, faster than 100.00% of Java online submissions for Range Sum of BST.
//Memory Usage: 67.6 MB, less than 26.16% of Java online submissions for Range Sum of BST.