Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a9ddd44

Browse files
author
openset
committed
Add: Range Sum of BST
1 parent 4d3a247 commit a9ddd44

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,25 @@
11
package range_sum_of_bst
2+
3+
import . "github.com/openset/leetcode/internal/kit"
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* type TreeNode struct {
8+
* Val int
9+
* Left *TreeNode
10+
* Right *TreeNode
11+
* }
12+
*/
13+
func rangeSumBST(root *TreeNode, L int, R int) int {
14+
ans := 0
15+
if root.Val >= L && root.Val <= R {
16+
ans += root.Val
17+
}
18+
if root.Left != nil && root.Val > L {
19+
ans += rangeSumBST(root.Left, L, R)
20+
}
21+
if root.Right != nil && root.Val < R {
22+
ans += rangeSumBST(root.Right, L, R)
23+
}
24+
return ans
25+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,37 @@
11
package range_sum_of_bst
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
input []int
11+
l int
12+
r int
13+
expected int
14+
}
15+
16+
func TestRangeSumBST(t *testing.T) {
17+
tests := [...]caseType{
18+
{
19+
input: []int{10, 5, 15, 3, 7, NULL, 18},
20+
l: 7,
21+
r: 15,
22+
expected: 32,
23+
},
24+
{
25+
input: []int{10, 5, 15, 3, 7, 13, 18, 1, NULL, 6},
26+
l: 6,
27+
r: 10,
28+
expected: 23,
29+
},
30+
}
31+
for _, tc := range tests {
32+
output := rangeSumBST(SliceInt2TreeNode(tc.input), tc.l, tc.r)
33+
if output != tc.expected {
34+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
35+
}
36+
}
37+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /