Wednesday, July 28, 2021

LintCode 1704 · Range Sum of BST.java

/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
// Approach #1 - More Readable recursion
public class Solution {
/**
* @param root: the root node
* @param L: an integer
* @param R: an integer
* @return: the sum
*/
public int rangeSumBST(TreeNode root, int L, int R) {
// write your code here.
if (root == null || L > R) {
return 0;
}
int ans = (L <= root.val && root.val <= R) ? root.val : 0;
if (root.val > L) {
ans += rangeSumBST(root.left, L, R);
}
if (root.val < R) {
ans += rangeSumBST(root.right, L, R);
}
return ans;
}
}
// Approach #2 - Tail recursion
// public class Solution {
// /**
// * @param root: the root node
// * @param L: an integer
// * @param R: an integer
// * @return: the sum
// */
// public int rangeSumBST(TreeNode root, int L, int R) {
// // write your code here.
// if (root == null || L > R) {
// return 0;
// }
// return rangeSumBST(root.left, L, R) +
// rangeSumBST(root.right, L, R) +
// ((root.val >= L && root.val <= R) ? root.val : 0);
// }
// }

No comments:

Post a Comment