博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
938. Range Sum of BST(python+cpp)
阅读量:3700 次
发布时间:2019-05-21

本文共 1764 字,大约阅读时间需要 5 分钟。

题目:

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.
Example 1:

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

Example 2:

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

Note:

The number of nodes in the tree is at most 10000.
The final answer is guaranteed to be less than 231.

解释:

中序遍历。
python代码:

# Definition for a binary tree node.# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    def rangeSumBST(self, root, L, R):        """        :type root: TreeNode        :type L: int        :type R: int        :rtype: int        """        self.sum=0        def mid(root):            if root.left:                mid(root.left)            if root.val>=L and root.val<=R:                self.sum+=root.val            if root.right:                mid(root.right)        if root:            mid(root)        return self.sum

c++代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {
public: int global_sum=0; int global_L; int global_R; int rangeSumBST(TreeNode* root, int L, int R) {
global_L=L; global_R=R; if (root) mid(root); return global_sum; } void mid(TreeNode* root) {
if (root->left) mid(root->left); if(root->val>=global_L && root->val<=global_R) global_sum+=root->val; if(root->right) mid(root->right); } };

总结:

暴力中序遍历,恩

转载地址:http://srlcn.baihongyu.com/

你可能感兴趣的文章
推荐几个单机游戏下载网、高质量图片下载网
查看>>
数据库查询
查看>>
单臂路由配置
查看>>
静态路由及动态路由 RIP配置
查看>>
现代密码学:AES
查看>>
现代密码学:密码协议
查看>>
现代密码学:密钥管理
查看>>
数据库增删改
查看>>
RSA公钥
查看>>
【总】现代密码学复习要点总结(谷利泽)
查看>>
【sql-server 数据库 命令大全】
查看>>
数据结构与算法
查看>>
C/C++总结
查看>>
计算机组成原理总结
查看>>
1.3 QT界面美化
查看>>
2 QT数据传输(MVC)
查看>>
3.QT逻辑交互(信号槽)
查看>>
4 QT功能模块
查看>>
(4)功能模块(文件)
查看>>
@Component 和 @Bean 的区别
查看>>