Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 938. Range Sum of BST

Rain Hu

938. Range Sum of BST


一、題目

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].

Example 1:
bst1

Example 2: bst2

Constraints:


二、分析

三、解題

1. DFS

int rangeSumBST(TreeNode* root, int low, int high) {
    if (!root) return 0;
    int sum = root->val <= high && root->val >= low ? root->val : 0;
    return sum + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}

2. Binary Search Tree

int rangeSumBST(TreeNode* root, int low, int high) {
    if (!root) return 0;
    int val = root->val >= low && root->val <= high ? root->val : 0;
    int left = root->val < low ? 0 : rangeSumBST(root->left, low, high);
    int right = root->val > high ? 0 : rangeSumBST(root->right, low, high);
    return left + right + val;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 872. Leaf-Similar Trees
Next
[LeetCode] 328. Odd Even Linked List