获取高度
Coddy AVL 树:数据结构系列 #10 课程的第 5 课,共 16 课。
为 AVLTree 添加一个 getHeight 方法,用来读取节点存储的高度。唯一需要注意的是空值情况:空子树并不存在,因此按惯例,它的高度为 0,比真实叶节点的高度 1 小 1。
通过这个方法统一获取所有高度,而不是到处直接读取 node.height,就只需要编写一次空值检查。
挑战
入门在 AVLTree 上编写一个方法 getHeight(node):如果 node 为 null,则返回 0;否则返回 node.height。
亲手试试
#include <stdio.h>
#include <string.h>
#include "avltree.h"
int main(void) {
AVLTree* tree = AVLTree_create();
char line[256];
while (fgets(line, sizeof(line), stdin) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (strcmp(line, "null") == 0) {
printf("%d\n", AVLTree_getHeight(tree, NULL));
}
if (strcmp(line, "null") != 0) {
int h;
sscanf(line, "%d", &h);
Node* n = Node_create(0);
n->height = h;
printf("%d\n", AVLTree_getHeight(tree, n));
}
}
return 0;
}
AVL 树:数据结构系列 #10中的所有课
自己练习: C 在线编译器