数据结构算法操作试题(C++/Python/Go)——938 二叉搜索树的范围和

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python/Go)——938 二叉搜索树的范围和,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
1. 题目

leetcode 链接:https://leetcode-cn.com/problems/range-sum-of-bst/

2. 解答

Go 156 ms, 80%

/**
 * 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
    }
    if root.Val < L {
        return rangeSumBST(root.Right, L, R)
    } else if root.Val > R {
        return rangeSumBST(root.Left, L, R)
    } else {
        return root.Val + rangeSumBST(root.Left, L, R) + rangeSumBST(root.Right, L, R)
    }
}