Skip to content

Commit dd4b665

Browse files
committed
Adjust RangeSumOfBST task solution. Take into account that it's search tree, not just binary tree
1 parent a9c7d54 commit dd4b665

1 file changed

Lines changed: 11 additions & 13 deletions

File tree

src/main/java/by/andd3dfx/tree/RangeSumOfBST.java

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.ArrayDeque;
44
import java.util.Deque;
5+
import lombok.AllArgsConstructor;
56

67
/**
78
* <pre>
@@ -31,10 +32,10 @@ public static int rangeSumBST_usingQueue(TreeNode root, int low, int high) {
3132
var sum = 0;
3233
while (!queue.isEmpty()) {
3334
var element = queue.pop();
34-
if (element.left != null) {
35+
if (element.left != null && root.val >= low) {
3536
queue.add(element.left);
3637
}
37-
if (element.right != null) {
38+
if (element.right != null && root.val <= high) {
3839
queue.add(element.right);
3940
}
4041
if (low <= element.val && element.val <= high) {
@@ -45,20 +46,23 @@ public static int rangeSumBST_usingQueue(TreeNode root, int low, int high) {
4546
}
4647

4748
public static int rangeSumBST_usingRecursion(TreeNode root, int low, int high) {
48-
return recursion(root, low, high);
49-
}
50-
51-
private static int recursion(TreeNode root, int low, int high) {
5249
if (root == null) {
5350
return 0;
5451
}
55-
int result = recursion(root.left, low, high) + recursion(root.right, low, high);
52+
int result = 0;
53+
if (root.val >= low) {
54+
result += rangeSumBST_usingRecursion(root.left, low, high);
55+
}
56+
if (root.val <= high) {
57+
result += rangeSumBST_usingRecursion(root.right, low, high);
58+
}
5659
if (low <= root.val && root.val <= high) {
5760
result += root.val;
5861
}
5962
return result;
6063
}
6164

65+
@AllArgsConstructor
6266
public static class TreeNode {
6367

6468
int val;
@@ -68,11 +72,5 @@ public static class TreeNode {
6872
TreeNode(int val) {
6973
this.val = val;
7074
}
71-
72-
TreeNode(int val, TreeNode left, TreeNode right) {
73-
this.val = val;
74-
this.left = left;
75-
this.right = right;
76-
}
7775
}
7876
}

0 commit comments

Comments
 (0)