美文网首页
938. Range Sum of BST

938. Range Sum of BST

作者: matrxyz | 来源:发表于2020-08-20 12:04 被阅读0次

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.

Solution:分治

思路:

Time Complexity: O() Space Complexity: O()

Solution Code:

class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        if (root == null) {
            return 0;
        }
        
        int sum = 0;
        if (L < root.val) {
            sum += rangeSumBST(root.left, L, R);
        }
        if (root.val < R) {
            sum += rangeSumBST(root.right, L, R);
        }
        if (L <= root.val && root.val <= R) {
            sum += root.val;
        }
        
        return sum;
    }
}

相关文章

网友评论

      本文标题:938. Range Sum of BST

      本文链接:https://www.haomeiwen.com/subject/jiysjktx.html