題目
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.
解答
題目的意思是說,給一個範圍[L, R] 然後將BST中在這個範圍的數累加起來,求這個和。
解法就是,遞歸遍歷,判斷當前節點是否滿足條件,滿足條件就累加進一個int裏面。當前節點好辦,只要判斷滿足範圍就可以了。那怎麼判斷左節點和右節點要不要處理呢?根據BST的特性(left < root < right)。
我們先考慮一下,什麼時候要遞歸左節點。假設當前節點在範圍內,那麼左節點就是不確定的,如果當前節點都不在範圍內,左節點就更不在範圍了。
所以:
if (curr.val > L) {
// 處理左節點
}
if (curr.val < L) {
// 當前節點都小於L了,那麼左節點就更小於L,就談不上處理了。
}
代碼就如下了:
static int ans = 0;
public int rangeSumBST(TreeNode root, int L, int R) {
ans = 0;
dfs(root, L, R);
return ans;
}
static void dfs(TreeNode root, int L, int R) {
if (root != null) {
if (root.val >= L && root.val <= R) {
ans += root.val;
}
if (root.val > L) {
dfs(root.left, L, R);
}
if (root.val < R) {
dfs(root.right, L, R);
}
}
}