L938二叉搜索树的范围和
GitHub 账户:LuvnJoae 欢迎关注! https://github.com/LuvnJoae
GitHub 代码链接:https://github.com/LuvnJoae/Java_leetcode
思路与结果
代码
思路1
package Day10_5_16.L938;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
int sum = 0;
if ( root != null){
if ( root.val >= L && root.val <= R ){
sum += root.val;
}
sum += rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
}
return sum;
}
}
思路2
package Day10_5_16.L938;
public class Solution2 {
public int rangeSumBST(TreeNode root, int L, int R) {
int sum = 0;
if (root != null) {
if (root.val >= L && root.val <= R) {
sum += root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
} else if (root.val < L) {
sum += rangeSumBST(root.right, L, R);
} else if (root.val > R) {
sum += rangeSumBST(root.left, L, R);
}
}
return sum;
}
}