938. Range Sum of BST

题目

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);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章