题目链接: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。
第一种做法就是用中序遍历,将大于L并且小于R的值累加起来,由于我是用java写的,在Solution类里添加public static变量当作全局变量的时候莫名的会报错,所以就用一个ArrayList来存储然后累加
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static int rangeSumBST(TreeNode root, int L, int R) {
ArrayList<Integer> dis = new ArrayList<>();
Mid(root,L,R,dis);
int sum = R + L;
for(int i=0;i<dis.size();i++){
sum += dis.get(i);
}
return sum;
}
public static void Mid(TreeNode root , int L,int R,ArrayList<Integer> dis){
if (root != null){
if(root.left != null)
Mid(root.left,L,R,dis);
if(root.val > L && root.val <R){
dis.add(root.val);
}
if(root.right != null)
Mid(root.right,L,R,dis);
}
}
}
第二种方法就是递归,有这么几种情况:节点的值小于L,节点的值大于R,节点的值大于L并且小于R,节点为空,所以我们可以以这四种情况作为条件进行判断
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static int dis;
public static int rangeSumBST(TreeNode root, int L, int R) {
if (root == null || R < L) //节点为空
return 0;
if(root.val < L) //节点值小于L,遍历该节点右子树的节点
return rangeSumBST(root.right,L,R);
if(root.val > R) //节点值大于R,遍历该节点左子树的节点
return rangeSumBST(root.left,L,R);
//符合条件,将节点值与遍历左子树的节点值和遍历右子树的节点值加起来返回
return root.val + rangeSumBST(root.left,L,R) + rangeSumBST(root.right,L,R);
}
}
本文介绍了两种解决二叉搜索树区间和问题的方法:中序遍历和递归。通过实例展示了如何在给定的二叉搜索树中找到所有结点值在L和R之间的值的总和。第一种方法使用中序遍历,将符合条件的值存储在ArrayList中再求和;第二种方法采用递归策略,根据节点值与区间的相对位置决定遍历方向。
492

被折叠的 条评论
为什么被折叠?



