diff --git a/problems/range-sum-of-bst/range_sum_of_bst.go b/problems/range-sum-of-bst/range_sum_of_bst.go index c5074b746..9146be989 100644 --- a/problems/range-sum-of-bst/range_sum_of_bst.go +++ b/problems/range-sum-of-bst/range_sum_of_bst.go @@ -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 +} diff --git a/problems/range-sum-of-bst/range_sum_of_bst_test.go b/problems/range-sum-of-bst/range_sum_of_bst_test.go index c5074b746..029889606 100644 --- a/problems/range-sum-of-bst/range_sum_of_bst_test.go +++ b/problems/range-sum-of-bst/range_sum_of_bst_test.go @@ -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) + } + } +}