Search
Duplicate
📗

트리 순회

주차
문제번호
1991
언어
C++
티어
실버
유형
트리
재귀
nj_Blog
nj_상태
이해도
100%
풀이
사람
이해도 2
13 more properties

문제접근

dfs로 순회를 할때 출력을 언제 해줄지 결정을 해주면 됨

놓쳤던 부분

초기화를 안 해두면 같은 환경에서 여러번 테스트할때 영향을 받을 수 있기 때문에 이왕이면 항상 초기화 해두는 습관이 좋을듯

코드

2024 KB

0 ms

#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; vector<vector<char> > graph; bool visited[26]; void dfs1(char node) { if (node == '.') return ; cout << node; for (unsigned int i = 0; i < 2; i++) dfs1(graph[node - 'A'][i]); } void dfs3(char node) { if (node == '.') return ; for (unsigned int i = 0; i < 2; i++) dfs3(graph[node - 'A'][i]); cout << node; } void dfs2(char node) { if (node == '.') return ; for (unsigned int i = 0; i < 2; i++) { dfs2(graph[node - 'A'][i]); if (!visited[node - 'A']) { visited[node - 'A'] = true; cout << node; } } } int main(void) { int n; char input1,input2, input3; ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; graph.resize(n, vector<char>(2)); for (int i = 0; i < n; i++) { cin >> input1 >> input2 >> input3; graph[input1 - 'A'][0] = input2; graph[input1 - 'A'][1] = input3; } fill(visited, visited + 26, false); dfs1('A'); cout << "\n"; dfs2('A'); cout << "\n"; dfs3('A'); return (0); }
C++
복사