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.

Example 1:

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

Example 2:

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

分析


给定一颗二叉树,以及 L,R,求值在 L,R 范围内的节点的值的和。

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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
"""
if root == None:
return 0
now_item = root.val if L <= root.val and root.val <= R else 0
return self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R) + now_item

解决方案2(Python)


剪个枝,风味更佳。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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
"""
if root == None:
return 0
sum = 0
if L <= root.val and root.val <= R:
sum += root.val
if root.val > L:
sum += self.rangeSumBST(root.left, L, R)
if root.val < R:
sum += self.rangeSumBST(root.right, L, R)
return sum

解决方案3(Rust)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, l: i32, r: i32) -> i32 {
if let Some(root) = root {
let mut sum = 0;
if l <= root.borrow().val && root.borrow().val <= r {
sum += root.borrow().val;
}

if l < root.borrow().val {
sum += Self::range_sum_bst(root.borrow().left.clone(), l, r);
}
if r > root.borrow().val {
sum += Self::range_sum_bst(root.borrow().right.clone(), l, r);
}
return sum;
}
return 0;
}
}

题目来源