티스토리 뷰
반응형
백준 1991번 트리 순회
https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net



정답 코드
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdio>
#define ull long long int
using namespace std;
struct Node
{
int ID;
Node* Left;
Node* Right;
};
Node* arr[30];
void preorder(Node *n)
{
cout << char(n->ID + 'A');
if (n->Left != nullptr)
preorder(n->Left);
if (n->Right != nullptr)
preorder(n->Right);
return;
}
void inorder(Node* n)
{
if (n->Left != nullptr)
inorder(n->Left);
cout << char(n->ID + 'A');
if (n->Right != nullptr)
inorder(n->Right);
return;
}
void postorder(Node* n)
{
if (n->Left != nullptr)
postorder(n->Left);
if (n->Right != nullptr)
postorder(n->Right);
cout << char(n->ID + 'A');
return;
}
int main(void)
{
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
Node* n = new Node();
n->ID = i;
arr[i] = n;
}
for (int i = 0; i < N; i++)
{
int ID, IDL, IDR;
char N, L, R;
cin >> N >> L >> R;
ID = (int)N - 'A';
IDL = (int)L - 'A';
IDR = (int)R - 'A';
if (IDL != -19)
arr[ID]->Left = arr[IDL];
if (IDR != -19)
arr[ID]->Right = arr[IDR];
}
// 탐색 진행
preorder(arr[0]);
cout << '\n';
inorder(arr[0]);
cout << '\n';
postorder(arr[0]);
return 0;
}
문제 풀이
트리를 순회하는 방식은 크게 3가지가 있습니다. 전위 순회(preorder), 중위순회(inorder), 후위순회(postorser)입니다. 코드를 구현하는 방식은 그리 어렵지 않습니다. 재귀를 이용해서 구현하면 됩니다.
전위 순회
루트-> 왼쪽 자식-> 오른쪽 자식
중위 순회
왼쪽 자식-> 루트-> 오른쪽 자식
후위 순회
왼쪽 자식-> 오른쪽 자식 -> 루트
그리고 구조체를 사용해서 구현하였습니다. 연결 리스트를 구현하는 방식이랑 비슷하다고 생각하면 될 것 같습니다.
반응형
'Algorithm > BOJ' 카테고리의 다른 글
백준 2108번 C++ (0) | 2023.08.04 |
---|---|
백준 2003번 C++ (0) | 2023.08.04 |
백준 1990번 C++ (0) | 2023.08.04 |
백준 1978번 C++ (0) | 2023.08.04 |
백준 1977번 C++ (0) | 2023.08.03 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- c++ string
- DFS
- 투 포인터
- 스택
- Do it!
- 이분 매칭
- 유클리드 호제법
- BFS
- C++ Stack
- js
- 자료구조
- 백준 풀이
- CSS
- 에라토스테네스의 체
- C++
- 자바스크립트
- 스프링 부트 crud 게시판 구현
- 알고리즘 공부
- 카운팅 정렬
- 유니온 파인드
- HTML5
- html
- 반복문
- 우선순위 큐
- 백준
- 세그먼트 트리
- java
- 알고리즘
- DP
- 자바
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함