Range Sum of BST

EasyTreeDepth-First SearchBinary Search TreeBinary Tree

Solution

import { TreeNode } from '@algorithm/lib';
 
export function rangeSumBST(root: TreeNode | null, low: number, high: number): number {
  if (root === null) {
    return 0;
  }
  if (low <= root.val && root.val <= high) {
    return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
  } else if (root.val < low) {
    return rangeSumBST(root.right, low, high);
  } else {
    return rangeSumBST(root.left, low, high);
  }
}