Skip to content

LeetCode: 938-Range Sum of BST 解題紀錄

Last Updated on 2022-12-07 by Clay

題目

Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

Constraints:

  • The number of nodes in the tree is in the range [1, 2 * 104].
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • All Node.val are unique.


題目給定兩個整數 low 以及 high,而我們要做的就是把二元搜索樹中在 [low, high] 範圍中的所有節點數值加總並返回。


解題思路

這題目第一感想到的就是使用遞迴去解,並隨時判斷是否該將子節點放入遞迴函式中。比方說,如果當前節點的數值已經小於 low,那麼便沒有必要將當前節點的左節點繼續進行遞迴...... 這也是一種剪枝的動作,稍微提升一些速度。

=== (2022-12-07 更新) ===

回頭看一年前寫的程式碼,覺得可讀性不怎麼樣。所以 C++ 的部份重新修改過了,感覺這樣比較好懂。


C++ 範例程式碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rangeSumBST(TreeNode* root, int low, int high) {
        // Base case
        if (!root) {
            return 0;
        }

        // Init
        int rangeSum = 0;

        // If the value of root is inclusive [low, high].
        if (root->val >= low && root->val <= high) {
            rangeSum += root->val;
        }

        // Check the left node and right node
        rangeSum += rangeSumBST(root->left, low, high);
        rangeSum += rangeSumBST(root->right, low, high);

        return rangeSum;
    }
};



Python 範例程式碼

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        # Init
        ans = root.val if root.val >= low and root.val <= high else 0
        
        # Iter
        if root.left and root.val > low:
            ans += self.rangeSumBST(root.left, low, high)
        
        if root.right and root.val < high:
            ans += self.rangeSumBST(root.right, low, high)
                
        return ans



References


Read More

Leave a Reply