높이 구하기
Coddy의 AVL 트리 - 자료구조 시리즈 #10 코스 레슨 — 16개 중 5번째.
노드의 저장된 높이를 읽는 getHeight 메서드를 AVLTree에 추가하세요. 유일한 주의 사항은 null 케이스입니다. 빈 서브트리는 존재하지 않으므로, 관례상 그 높이는 실제 리프 노드의 높이인 1보다 하나 적은 0입니다.
모든 높이 조회를 (어디서나 node.height를 직접 읽는 대신) 이 하나의 메서드를 통해 라우팅하면 null 체크를 한 번만 작성하면 된다는 의미입니다.
챌린지
초급AVLTree에 node가 null이면 0을 반환하고, 그렇지 않으면 node.height를 반환하는 getHeight(node) 메서드를 작성하세요.
직접 해보기
#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;
}