728x90
조직 구조도 만들기 (이진 트리 이용)
서론
트리(Tree) 자료구조를 이용하여 조직 구조도를 만들어보자.
이진 트리(Binary Tree)를 이용하고, 1명의 상사 직원 밑에 2명의 부하 직원을 둘 수 있다고 가정한다.
상사 직원이 없을 경우, 부하 직원을 추가할 수 없다.

코드
#include <iostream>
#include <queue>
struct node {
std::string position;
node* first;
node* second;
};
struct org_tree {
node* root;
static org_tree create_org_structure(const std::string& pos) {
org_tree tree;
tree.root = new node {pos, NULL, NULL};
return tree;
}
static node* find(node* root, const std::string& value) {
if (root == NULL) {
return NULL;
}
if (root->position == value) {
return root;
}
// 왼쪽 서브 트리 검사
auto firstFound = org_tree::find(root->first, value);
if (firstFound != NULL) {
return firstFound;
}
// 오른쪽 서브 트리 검사
return org_tree::find(root->second, value);
}
bool addSubordinate(const std::string& manager, const std::string& subordinate) {
auto managerNode = org_tree::find(root, manager);
//// 1. 부하 직원 추가 실패
// 상사 직원이 없을 경우
if (!managerNode) {
std::cout << manager << "을(를) 찾을 수 없습니다: " << std::endl;
return false;
}
// 상사 직원 밑에 이미 2명의 부하 직원이 있을 경우
if (managerNode->first && managerNode->second) {
std::cout << manager << " 아래에 " << subordinate << "을(를) 추가할 수 없습니다." << std::endl;
return false;
}
//// 2. 부하 직원 추가 성공
// 상사 직원 밑에 부하 직원이 없을 경우
if (!managerNode->first) { // (1) 첫번째(first) 부하 직원이 없을 경우
managerNode->first = new node {subordinate, NULL, NULL};
}
else { // (2) 2번째(second) 부하 직원이 없을 경우
managerNode->second = new node {subordinate, NULL, NULL};
}
std::cout << manager << " 아래에 " << subordinate << "을(를) 추가했습니다." << std::endl;
return true;
}
};
int main() {
auto tree = org_tree::create_org_structure("CEO");
tree.addSubordinate("CEO", "부사장");
tree.addSubordinate("부사장", "IT부장");
tree.addSubordinate("부사장", "마케팅부장");
tree.addSubordinate("IT부장", "보안팀장");
tree.addSubordinate("IT부장", "앱개발팀장");
tree.addSubordinate("마케팅부장", "물류팀장");
tree.addSubordinate("마케팅부장", "홍보팀장");
return 0;
}
결과 확인
CEO 아래에 부사장을(를) 추가했습니다.
부사장 아래에 IT부장을(를) 추가했습니다.
부사장 아래에 마케팅부장을(를) 추가했습니다.
IT부장 아래에 보안팀장을(를) 추가했습니다.
IT부장 아래에 앱개발팀장을(를) 추가했습니다.
마케팅부장 아래에 물류팀장을(를) 추가했습니다.
마케팅부장 아래에 홍보팀장을(를) 추가했습니다.728x90
'Source Code > C++' 카테고리의 다른 글
| [C++] 3개의 숫자 중에서 최댓값 구하기 (max(a, b, c)) (0) | 2022.12.13 |
|---|---|
| [C++] STL로 해시 테이블(Hash Table) 만들기 (std::unordered_map, std::unordered_set) (0) | 2021.05.28 |
| [C++] 다양한 타입의 데이터 여러 개를 인자로 받아 공통 타입으로 변환하는 함수 (0) | 2021.05.08 |
| [C++] 정수를 입력 받아 각 자릿수의 합 구하기 (0) | 2021.02.17 |
| Python Range() 함수 구현 (0) | 2021.01.20 |
| 0부터 N까지 피보나치 수열 나열하기 (0) | 2020.12.28 |
| 숫자 N의 약수의 개수 구하기 (0) | 2020.12.26 |
| 0부터 n까지의 숫자의 2진수 출력하기 (0) | 2017.10.10 |