Back to Leetcode Go

938. Range Sum of BST

website/content.en/ChapterFour/0900~0999/0938.Range-Sum-of-BST.md

1.7.971.9 KB
Original Source

938. Range Sum of BST

Problem

Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].

Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23

Constraints:

  • The number of nodes in the tree is in the range [1, 2 * 10^4].
  • 1 <= Node.val <= 10^5
  • 1 <= low <= high <= 10^5
  • All Node.val are unique.

Summary

Given the root node root of a binary search tree, return the sum of the values of all nodes whose values are within the range [low, high].

Solution Approach

  • Easy problem. Because of the ordered property of a binary search tree, preorder traversal is ordered. During traversal, determine whether the node value is within the interval range; if it is within the interval, add it to the sum, and if it is not within the interval, ignore the node. Finally output the accumulated sum.

Code

go
package leetcode

import (
	"github.com/halfrost/leetcode-go/structures"
)

// TreeNode define
type TreeNode = structures.TreeNode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func rangeSumBST(root *TreeNode, low int, high int) int {
	res := 0
	preOrder(root, low, high, &res)
	return res
}

func preOrder(root *TreeNode, low, high int, res *int) {
	if root == nil {
		return
	}
	if low <= root.Val && root.Val <= high {
		*res += root.Val
	}
	preOrder(root.Left, low, high, res)
	preOrder(root.Right, low, high, res)
}