LeetCode 938. 二叉搜索树的范围和

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

给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。

二叉搜索树保证具有唯一的值。

 

示例 1:

输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例 2:

输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
 

提示:

树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 int rangeSumBST(struct TreeNode* root, int L, int R){
10     if(root==NULL) return 0;
11     if(root->val>=L&&root->val<=R){
12         return root->val+rangeSumBST(root->left,L,R)+rangeSumBST(root->right,L,R);
13     }else if(root->val<L){
14         return rangeSumBST(root->right,L,R);
15     }else{
16         return rangeSumBST(root->left,L,R);
17     }
18 }

 

posted @ 2019-08-13 08:52  wydxry  阅读(449)  评论(0编辑  收藏  举报
Live2D