【Lintcode】1704. Range Sum of BST

題目地址:

https://www.lintcode.com/problem/range-sum-of-bst/description

給定一棵BST,再給定區間[L,R][L,R],求BST中所有屬於這個區間的數字之和。

思路是遞歸,如果樹根小於LL則只需返回右子樹的range sum,類似如果樹根大於RR則只需返回左子樹的range sum,否則返回樹根加上左右子樹的range sum。代碼如下:

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) {
            return 0;
        }
        
        if (root.val < L) {
            return rangeSumBST(root.right, L, R);
        }
        if (root.val > R) {
            return rangeSumBST(root.left, L, R);
        }
        
        return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

時間複雜度O(n)O(n),空間O(h)O(h)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章