Menu
CoddyTech

区间和

Coddy AVL 树:数据结构系列 #10 课程的第 13 课,共 16 课。

由于树会按顺序保存所有值,因此求一个范围内所有值的和时,你不必检查每个节点:当某个节点的值小于 low 时,它的整个左子树也都小于 low,可以跳过;当某个节点的值大于 high 时,右子树也可以用同样的逻辑处理。

只需进行简单的中序遍历,并且只递归遍历可能包含范围内值的子树即可。不过,对于这个挑战,先完整遍历,再进行筛选也可以。

challenge icon

挑战

简单

编写一个函数 rangeSum(tree, low, high),返回树中所有介于 low 和 high 之间(包括这两个值)的值的总和。

亲手试试

#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;
}

AVL 树:数据结构系列 #10中的所有课

自己练习: C 在线编译器