Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 투 포인터
- ue5
- 트리
- 정렬
- 다이나믹 프로그래밍
- 그래프
- 백트래킹
- 알고리즘
- 유니온 파인드
- 구현
- 스택
- 그리디 알고리즘
- 백준
- 우선순위 큐
- 누적 합
- 자료구조
- DFS
- 시뮬레이션
- 문자열
- VR
- XR Interaction Toolkit
- c++
- 유니티
- 수학
- BFS
- 브루트포스
- 재귀
- Team Fortress 2
- 다익스트라
- Unreal Engine 5
Archives
- Today
- Total
1일1알
백준 1991번 트리 순회 C++ 본문
노드와 트리를 직접 만들어서 풀다가 좀 오래걸렸는데 다른사람들 푼 것을 보니까 map으로 쉽게 풀 수 있었다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
struct Node {
Node* parent = nullptr;
Node* left = nullptr;
Node* right = nullptr;
char value;
};
Node* root = nullptr;
Node* FindNode(Node* curr, char value) {
if (curr->value == value)
return curr;
Node* left = nullptr;
Node* right = nullptr;
if (curr->left)
left = FindNode(curr->left, value);
if (curr->right)
right = FindNode(curr->right, value);
if (left != nullptr)
return left;
return right;
}
void Insert(char parent, char left, char right) {
Node* currNode;
if (root == nullptr) {
currNode = new Node();
currNode->value = parent;
root = currNode;
}
else {
currNode = FindNode(root, parent);
}
if (left != '.') {
Node* leftNode = new Node();
currNode->left = leftNode;
leftNode->value = left;
leftNode->parent = currNode;
}
if (right != '.') {
Node* rightNode = new Node();
currNode->right = rightNode;
rightNode->value = right;
rightNode->parent = currNode;
}
}
void Print(Node* node, int traversalType) {
if (node == nullptr)
return;
if (traversalType == 0)
cout << node->value;
Print(node->left, traversalType);
if (traversalType == 1)
cout << node->value;
Print(node->right, traversalType);
if (traversalType == 2)
cout << node->value;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
char a, b, c;
cin >> a >> b >> c;
Insert(a, b, c);
}
Print(root, 0);
cout << "\n";
Print(root, 1);
cout << "\n";
Print(root, 2);
};
'알고리즘' 카테고리의 다른 글
백준 5639번 이진 검색 트리 C++ (0) | 2022.06.14 |
---|---|
백준 1916번 최소비용 구하기 C++ (0) | 2022.06.13 |
백준 1629번 곱셈 C++ (0) | 2022.06.11 |
백준 2407번 조합 C++ (0) | 2022.06.10 |
백준 1043번 거짓말 C++ (0) | 2022.06.09 |