
2025.04.13
오늘한 내용 : C - BT,BST
WEEK05: C Pointer(&, * 연산자), 동적 메모리 할당, Linked List, Stack, Queue, Binary Tree, Binary Search Tree, 동적 프로그래밍, 그리디 알고리즘
계속해서 C언어를 공부해보자
typedef struct _btnode{
int item;
struct _btnode *left;
struct _btnode *right;
} BTNode;
기본 상태 생각:
→ 비어 있는 트리의 높이는? → -1 (간선 수 기준)
→ → 이게 base case
작은 문제에 위임:
→ maxHeight(node->left)는 왼쪽 서브트리 높이를 구해준다
→ maxHeight(node->right)도 오른쪽 서브트리 높이를 구해준다
현재 노드는 뭘 하면 될까?
→ 왼쪽, 오른쪽 중 더 큰 쪽을 선택
→ 거기에 +1만 해주면 내 트리의 높이 완성
| 자료형 | 무한대 표현 | 설명 |
|---|---|---|
float | INFINITY, 1.0/0.0 | <math.h> |
double | HUGE_VAL, INFINITY | <math.h> |
int | INT_MAX | <limits.h>에서 상수로 정의, 가짜 무한대처럼 사용 |
| 타입 | 무한대 표현 (math.h 없이) | 설명 |
|---|---|---|
double, float | 1.0 / 0.0, -1.0 / 0.0 | inf, -inf 반환됨 |
int | 2147483647 큰 수 직접 사용 | 32비트 기준 INT_MAX 값 |
int hasGreatGrandchild(BTNode *node)
{
/* add your code here */
if (node ==NULL)
return -1; // 노드 없으면 높이 -1 / (간선 기준 계산).
int left = hasGreatGrandchild(node->left);
int right = hasGreatGrandchild(node->right);
// 간선 수가 3개 이상이면 증손자노드가 존재.
if (left >= 3 || right >= 3)
printf("%d ", node->item);
return (left > right) ? left + 1 : right + 1;
}
int hasGreatGrandchild(BTNode *node)
{
/* add your code here */
if (node ==NULL)
return -1; // 노드 없으면 높이 -1 / (간선 기준 계산).
int left = hasGreatGrandchild(node->left);
int right = hasGreatGrandchild(node->right);
int h = (left > right) ? left + 1 : right + 1;
// 간선 수가 3개 이상이면 증손자노드가 존재.
if (h >= 3)
printf("%d ", node->item);
return h;
}
n = dequeue(&q.head, &q.tail);
enqueue(&q.head, &q.tail, n->left);
void inOrderTraversal(BSTNode *root)
{
/* add your code here */
// left -> root -> right
if (root == NULL) return;
Stack stk;
stk.top = NULL;
BSTNode* cur = root;
while (!isEmpty(&stk) || cur != NULL){
// 일단 왼쪽 다담아
while(cur != NULL){
push(&stk,cur);
cur = cur -> left;
}
// 끝이니까 팝 후 출력
cur = pop(&stk);
printf("%d ", cur -> item);
//오른쪽으로
cur = cur -> right;
}
}
void preOrderIterative(BSTNode *root)
{
/* add your code here */
// root -> left -> right
if (root == NULL) return;
Stack stk;
stk.top = NULL;
push(&stk,root);
BSTNode* n;
while (!isEmpty(&stk)){
n = pop(&stk);
printf("%d ",n->item);
//오른쪽을 먼저 푸시해야 왼쪽이 먼저 나옴
if (n->right != NULL)
push(&stk,n->right);
if (n->left != NULL)
push(&stk,n->left);
}
}
void inOrderTraversal(BSTNode *root)
{
/* add your code here */
// left -> root -> right
if (root == NULL) return;
Stack stk;
stk.top = NULL;
BSTNode* cur = root;
while (!isEmpty(&stk) || cur != NULL){
// 일단 왼쪽 담는데 루트는 출력
while(cur != NULL){
printf("%d ", cur -> item);
push(&stk,cur);
cur = cur -> left;
}
// 끝이니까 팝
cur = pop(&stk);
//오른쪽으로
cur = cur -> right;
}
}