Range Sum
Lesson 13 of 16 in Coddy's AVL Tree - Data Structures Series #10 course.
Because the tree keeps every value ordered, you don't need to inspect every single node to add up a range: whenever a node's value is below low, its entire left subtree is also below low and can be skipped, and the same logic applies to the right subtree when a node's value is above high.
A simple in-order walk that only recurses into subtrees that could contain values in range is enough, though for this challenge a full traversal with a filter works too.
Challenge
EasyWrite a function rangeSum(tree, low, high) that returns the sum of every value in the tree that falls between low and high, inclusive.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avltree.h"
#include "solution.h"
int main(void) {
AVLTree* tree = AVLTree_create();
char line1[4096];
fgets(line1, sizeof(line1), stdin);
char* tok = strtok(line1, " \n");
while (tok != NULL) {
AVLTree_insert(tree, atoi(tok));
tok = strtok(NULL, " \n");
}
char line2[256];
fgets(line2, sizeof(line2), stdin);
int p0 = atoi(strtok(line2, " \n"));
int p1 = atoi(strtok(NULL, " \n"));
int result = rangeSum(tree, p0, p1);
printf("%d\n", result);
return 0;
}
All lessons in AVL Tree - Data Structures Series #10
3Practice Challenges
Kth Smallest ElementRange SumLowest Common AncestorLevel Order TraversalSuccessor Of A Value