darekfive

938. Range Sum of BST - Precompute

Feb 26th, 2025
1,367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode() {}
  8.  *     TreeNode(int val) { this.val = val; }
  9.  *     TreeNode(int val, TreeNode left, TreeNode right) {
  10.  *         this.val = val;
  11.  *         this.left = left;
  12.  *         this.right = right;
  13.  *     }
  14.  * }
  15.  */
  16. class Solution {
  17.     private List<Integer> values;
  18.     private int[] prefixSum;
  19.    
  20.     public int rangeSumBST(TreeNode root, int low, int high) {
  21.         values = new ArrayList<>();
  22.         inOrder(root);
  23.        
  24.         if (values.isEmpty()) return 0;
  25.        
  26.         prefixSum = new int[values.size()];
  27.         int sum = 0;
  28.         for (int i = 0; i < prefixSum.length; i++) {
  29.             prefixSum[i] = sum = sum + values.get(i);
  30.         }
  31.  
  32.         int left = Collections.binarySearch(values, low);
  33.         int right = Collections.binarySearch(values, high);
  34.        
  35.         // Handle cases where exact values aren't found
  36.         if (left < 0) left = -(left + 1);    // Insertion point
  37.         if (right < 0) right = -(right + 1) - 1; // Last index before insertion point
  38.        
  39.         // if (left >= values.size() || right < 0) return 0;
  40.        
  41.         // Adjust for inclusive range
  42.         if (left > 0) {
  43.             return prefixSum[right] - prefixSum[left - 1];
  44.         } else {
  45.             return prefixSum[right];
  46.         }
  47.     }
  48.    
  49.     private void inOrder(TreeNode node) {
  50.         if (node == null) return;
  51.         inOrder(node.left);
  52.         values.add(node.val);
  53.         inOrder(node.right);
  54.     }
  55. }
Advertisement