Topic Address:
https://leetcode.com/problems/range-sum-of-bst/
Given a binary search tree, give a fixed range , seeking in the tree at all numbers in this range and.
Divide and conquer. First determine whether the scope of the roots, if not, it can be a direct result of solving a subtree; otherwise calculate left and right subtrees in the range of the number and, coupled with the roots can be. code show as below:
public 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);
} else if (root.val > R) {
return rangeSumBST(root.left, L, R);
} else {
return rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R) + root.val;
}
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
time complexity , space 。