range-sum-of-bst.dart (757B)
1 //Take in three inputs where the first is the root of a tree, the second is the lowest value to add, and 2 //the third is the highest value to add. Given this traverse the tree and return the sum of all values 3 //between low and high. 4 //The time complexity of this code is O(n) where n is the number of nodes. 5 //My solution uses recursion and an inorder BFS algorithm. 6 //Time: 295ms Beats: 80% 7 //Memory: 164.7MB Beats: 10% 8 class Solution { 9 10 int rangeSumBST(TreeNode? root, int low, int high) { 11 if(root== null){ 12 return 0; 13 } 14 int sum = rangeSumBST(root.left, low, high); 15 sum += rangeSumBST(root.right, low, high); 16 if((root.val) >= low && (root.val) <= high){ 17 sum += (root.val); 18 } 19 return sum; 20 } 21 }