Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions problems/range-sum-of-bst/range_sum_of_bst.go
Original file line number Diff line number Diff line change
@@ -1 +1,25 @@
package range_sum_of_bst

import . "github.com/openset/leetcode/internal/kit"

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rangeSumBST(root *TreeNode, L int, R int) int {
ans := 0
if root.Val >= L && root.Val <= R {
ans += root.Val
}
if root.Left != nil && root.Val > L {
ans += rangeSumBST(root.Left, L, R)
}
if root.Right != nil && root.Val < R {
ans += rangeSumBST(root.Right, L, R)
}
return ans
}
36 changes: 36 additions & 0 deletions problems/range-sum-of-bst/range_sum_of_bst_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,37 @@
package range_sum_of_bst

import (
"testing"

. "github.com/openset/leetcode/internal/kit"
)

type caseType struct {
input []int
l int
r int
expected int
}

func TestRangeSumBST(t *testing.T) {
tests := [...]caseType{
{
input: []int{10, 5, 15, 3, 7, NULL, 18},
l: 7,
r: 15,
expected: 32,
},
{
input: []int{10, 5, 15, 3, 7, 13, 18, 1, NULL, 6},
l: 6,
r: 10,
expected: 23,
},
}
for _, tc := range tests {
output := rangeSumBST(SliceInt2TreeNode(tc.input), tc.l, tc.r)
if output != tc.expected {
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
}
}
}