Node 설계, 생성/해제, 순회, 높이 계산 구현PrintTree)와 높이 계산(GetHeight)을 직접 구현할 수 있다. R1 개발실 (루트)
/ | \
디자인 프로그래밍 아트
/|\ /|\ /|\
전투 경제 스토리 ...
| 용어 | 설명 |
|---|---|
| 루트(root) | 최상위 노드 |
| 부모/자식 | 바로 위/아래 연결 관계 |
| 형제(sibling) | 같은 부모를 가진 노드 |
| 리프(leaf) | 자식이 없는 노드 |
| 깊이(depth) | 루트에서 현재 노드까지 간선 수 |
| 높이(height) | 현재 노드에서 가장 깊은 리프까지 간선 수(또는 규약에 따라 노드 수) |
이 문서의 구현 예제는 “리프 높이 = 1(노드 수 기준)” 규약을 사용합니다.
재귀 사고법:
Node 모델struct Node
{
explicit Node(const std::string& data) : data(data) {}
std::string data;
std::vector<Node*> children;
};
std::vector<Node*>를 사용합니다.Node* CreateTree()
{
Node* root = new Node("R1 개발실");
Node* design = new Node("디자인");
Node* programming = new Node("프로그래밍");
Node* art = new Node("아트");
root->children.push_back(design);
root->children.push_back(programming);
root->children.push_back(art);
design->children.push_back(new Node("전투"));
design->children.push_back(new Node("경제"));
design->children.push_back(new Node("스토리"));
return root;
}
void DestroyTree(Node* root)
{
if (root == nullptr)
return;
for (Node* child : root->children)
DestroyTree(child);
delete root;
}
new)했다면 해제(delete)까지 짝을 맞춰야 합니다.void PrintTree(const Node* root, int depth = 0)
{
if (root == nullptr)
return;
std::cout << std::string(depth * 2, ' ') << root->data << '\n';
for (const Node* child : root->children)
PrintTree(child, depth + 1);
}
동작 원리:
복잡도:
O(N) (모든 노드 1회 방문)O(H) (H는 트리 높이)정의(본 문서 규약):
nullptr 높이 = 01int GetHeight(const Node* root)
{
if (root == nullptr)
return 0;
int maxChildHeight = 0;
for (const Node* child : root->children)
maxChildHeight = std::max(maxChildHeight, GetHeight(child));
return maxChildHeight + 1;
}
핵심:
PrintTree에서 depth 인자를 없애면 어떤 정보가 사라질까?GetHeight에서 리프 높이를 0으로 잡는 규약으로 바꾸려면 무엇을 수정해야 할까?CreateTree만 있고 DestroyTree가 없으면 어떤 문제가 생길까?