某个值的后继
Coddy AVL 树:数据结构系列 #10 课程的第 16 课,共 16 课。
一个值的中序后继是树中严格大于该值的最小值,也就是在排序后的列表中紧跟在该值后面的值。如果该值是树中的最大值,它就没有后继。
你可以只遍历一遍就找到它,无需排序:从根节点开始向下遍历,每当你越过一个太小的值向右走时,就记住你上一次向左走时经过的节点,把它作为目前最合适的候选节点。
挑战
简单编写一个函数 successor(tree, value),返回树中严格大于 value 的最小值;如果不存在这样的值,则返回 -1。
亲手试试
#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 result = successor(tree, p0);
printf("%d\n", result);
return 0;
}
AVL 树:数据结构系列 #10中的所有课
自己练习: C 在线编译器