LeetCode:938. Range Sum of BST

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.

Input:

root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32

目前遇到BST類型的題目都是有關遞迴的

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rangeSumBST(root *TreeNode, L int, R int) int {
   if root == nil {
        return 0
    }
    sum := 0
    if L<=root.Val && root.Val<=R {
        sum += root.Val
    }
    if L < root.Val {
        sum += rangeSumBST(root.Left, L, R)
    }
    if R > root.Val {
        sum += rangeSumBST(root.Right, L, R)
    }
    return sum
}

發佈留言