Range Sum of BST

easy tree bst dfs

Problem

Given the root of a BST and integers low and high, return the sum of all node values v with low ≤ v ≤ high.

Inputtree=[10,5,15,3,7,null,18], low=7, high=15
Output32
Prune subtree if all values are out of range thanks to BST ordering.

def rangeSumBST(root, low, high):
    if not root: return 0
    if root.val < low:  return rangeSumBST(root.right, low, high)
    if root.val > high: return rangeSumBST(root.left, low, high)
    return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high)
function rangeSumBST(root, low, high) {
  if (!root) return 0;
  if (root.val < low) return rangeSumBST(root.right, low, high);
  if (root.val > high) return rangeSumBST(root.left, low, high);
  return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
}
class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        if (root == null) return 0;
        if (root.val < low) return rangeSumBST(root.right, low, high);
        if (root.val > high) return rangeSumBST(root.left, low, high);
        return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
    }
}
int rangeSumBST(TreeNode* root, int low, int high) {
    if (!root) return 0;
    if (root->val < low) return rangeSumBST(root->right, low, high);
    if (root->val > high) return rangeSumBST(root->left, low, high);
    return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
Time: O(n) worst, O(k + log n) typical Space: O(h)