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 = 15Output: 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}

沒有留言:

張貼留言

About

努力在程式的大海
用力的揮動雙手
找出屬於自己的航線

Blog Archive

Traffic