题:https://leetcode.com/problems/range-sum-of-bst/description/
题目
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 2^31.
题目大意
在搜索二叉树中,求所有结点val在L与R之间 的和。
思路
利用搜索二叉树特性:在一个结点,其左子树结点val<root.val<其右子树结点val。
当root.val<=L 其左子树不用遍历;
当root.val>=R 其右子树不用遍历;
等价的:
root.val>L ,其左子树可能有满足 L<=val<=R 的结点,继续遍历。root.val<R,其右子树应该遍历
方法一 dfs
利用 dfs 先序遍历 ,选择正确的 子树遍历。将符合条件的 结点val 累加。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
public void dfs(TreeNode root, int L, int R){
if(root == null)
return;
if(L<=root.val && root.val<=R)
res += root.val;
if(root.val<R)
dfs(root.right,L,R);
if(root.val>L)
dfs(root.left,L,R);
}
public int rangeSumBST(TreeNode root, int L, int R) {
dfs(root,L,R);
return res;
}
}
方法二 递归
递归函数:int rangeSumBST(TreeNode root, int L, int R) 树root中结点val在[L,R]之间 的总和。
递归函数 转移方程:
rangeSumBST(root, L, R) = 1(if L<=root.val <=R ) + rangeSumBST(root.left, L, R) (if L<root.val ) + rangeSumBST(root.right, L, R)(if root.val<R)
终止条件:if root == null,return 0.
/**
* 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) {
if(root == null)
return 0;
int sum = 0;
if(L<=root.val && root.val<=R)
sum += root.val;
if(root.val<R)
sum += rangeSumBST(root.right,L,R);
if(root.val>L)
sum += rangeSumBST(root.left,L,R);
return sum;
}
}
更简写法
/**
* 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) {
if(root == null)
return 0;
if(root.val<L)
return rangeSumBST(root.right,L,R);
if(root.val>R)
return rangeSumBST(root.left,L,R);
return root.val + rangeSumBST(root.left,L,R) + rangeSumBST(root.right,L,R);
}
}