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:

  1. The number of nodes in the tree is at most 10000.
  2. The final answer is guaranteed to be less than 2^31.
 

Approach #1: C++. [recursive]

/**
* 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 rangeSumBST(TreeNode* root, int L, int R) {
ans = 0;
dfs(root, L, R);
return ans;
} private:
int ans; void dfs(TreeNode* root, int L, int R) {
if (root != NULL) {
if (L <= root->val && root->val <= R) {
ans += root->val;
}
if (L < root->val) {
dfs(root->left, L, R);
}
if (R > root->val) {
dfs(root->right, L, R);
}
}
}
};

  

Approach #2: Java. [Iterative]

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
int ans = 0;
Stack<TreeNode> stack = new Stack();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node != null) {
if (L <= node.val && node.val <= R)
ans += node.val;
if (L < node.val)
stack.push(node.left);
if (R > node.val)
stack.push(node.right);
}
}
return ans;
}
}

  

Approach #3: Python.

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
ans = 0
stack = [root]
while stack:
node = stack.pop()
if node:
if L <= node.val <= R:
ans += node.val
if L < node.val:
stack.append(node.left)
if R > node.val:
stack.append(node.right) return ans

  

最新文章

  1. ABP框架 - 多层结构
  2. Latex中画出函数文件的调用关系拓扑图
  3. [webgrid] &ndash; header - (How to Add custom html to Header in WebGrid)
  4. mysql的时间转化
  5. C# JSON字符串序列化与反序列化
  6. JS一些语法
  7. Subsequence
  8. Fatal error: Call to undefined function mysql_connect()
  9. Linux中命令行编译java接口总是提示找不到符号的疑难杂症的解决
  10. [Javascript] How to write a Javascript libarary
  11. Alter的用法(添加字段,删除字段,修改字段名)
  12. 有感于NC的强大
  13. hdu 2612 多终点BFS
  14. 20, CSS 定义选择器
  15. C#からネイティブDLLを呼び出す場合のVSからのデバッグのジレンマを解決する
  16. Noip数学整理
  17. OOP理解
  18. thinkphp 3.2.3 addAll方法的坑
  19. [BZOJ4444][SCOI2015]国旗计划(倍增)
  20. Gulp插件autoprefixer的使用

热门文章

  1. 利用wrapper注冊的 java服务起动超时的解决方法
  2. 2.2链表 链表中倒数第k个结点
  3. IOS AFNetWorking 设置超时时间
  4. MSSQL2005外网IP的1433端口开启方法
  5. make和rest用法
  6. Javascript类型转换的规则实例解析
  7. Protothread 机制
  8. PyQt5豆瓣镜像下快速安装
  9. HDU 6170 Two strings (dp)
  10. codeforces 706B B. Interesting drink(二分)