Skip to content

Commit 7d465a7

Browse files
author
Kohei Asai
authored
938. Range Sum of BST (axross#148)
1 parent a580c33 commit 7d465a7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

solutions/range_sum_of_bst.ts

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { BinaryTreeNode } from "../data_structures/binary_tree.ts";
2+
3+
// 938. Range Sum of BST
4+
// https://leetcode.com/problems/range-sum-of-bst/
5+
export default function rangeSumBST(
6+
node: BinaryTreeNode<number> | null,
7+
L: number,
8+
R: number
9+
): number {
10+
if (!node) return 0;
11+
12+
const leftSum = node.val > L ? rangeSumBST(node.left, L, R) : 0;
13+
const rightSum = node.val < R ? rangeSumBST(node.right, L, R) : 0;
14+
const self = node.val >= L && node.val <= R ? node.val : 0;
15+
16+
return leftSum + self + rightSum;
17+
}

solutions/range_sum_of_bst_test.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { test } from "https://deno.land/std/testing/mod.ts";
2+
import { assertStrictEq } from "https://deno.land/std/testing/asserts.ts";
3+
import { createBinaryTreeNode } from "../data_structures/binary_tree.ts";
4+
import rangeSumBST from "./range_sum_of_bst.ts";
5+
6+
test("938. Range Sum of BST", () => {
7+
assertStrictEq(
8+
rangeSumBST(createBinaryTreeNode([10, 5, 15, 3, 7, null, 18]), 7, 15),
9+
32
10+
);
11+
assertStrictEq(
12+
rangeSumBST(
13+
createBinaryTreeNode([10, 5, 15, 3, 7, 13, 18, 1, null, 6]),
14+
6,
15+
10
16+
),
17+
23
18+
);
19+
assertStrictEq(
20+
rangeSumBST(
21+
createBinaryTreeNode([10, 5, 15, 3, 7, 13, 18, 1, null, 6]),
22+
4,
23+
12
24+
),
25+
28
26+
);
27+
assertStrictEq(rangeSumBST(createBinaryTreeNode([1]), 1, 1), 1);
28+
assertStrictEq(rangeSumBST(createBinaryTreeNode([]), 1, 1), 0);
29+
});

0 commit comments

Comments
 (0)