백준 알고리즘
백준 알고리즘 11725번 : 트리의 부모 찾기
#include <iostream>
#include <vector>
using namespace std;
#define MAX 100001
vector<int> v[MAX];
int parent[MAX];
bool visited[MAX];
int N;
void findParent(int x) {
visited[x] = true;
for (int i = 0; i < v[x].size(); i++) {
int next = v[x][i];
if (visited[next] == false) {
parent[next] = x;
findParent(next);
}
}
}
int main(int argc, const char* argv[]) {
cin >> N;
int a, b;
for (int i = 1; i < N; i++) {
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
findParent(1);
for (int i = 2; i <= N; i++)
cout << parent[i] << '\n';
return 0;
}
백준 알고리즘 1991번 : 트리 순회
#include <iostream>
using namespace std;
int n;
struct node {
char left;
char right;
};
struct node arr[27];
void preOrder(char root) {
if (root == '.')
return;
cout << root;
preOrder(arr[root].left);
preOrder(arr[root].right);
}
void inOrder(char root) {
if (root == '.')
return;
inOrder(arr[root].left);
cout << root;
inOrder(arr[root].right);
}
void postOrder(char root) {
if (root == '.')
return;
postOrder(arr[root].left);
postOrder(arr[root].right);
cout << root;
}
int main(int argc, const char* argv[]) {
cin >> n;
char a, b, c;
for (int i = 1; i <= n; i++) {
cin >> a >> b >> c;
arr[a].left = b;
arr[a].right = c;
}
preOrder('A');
cout << "\n";
inOrder('A');
cout << "\n";
postOrder('A');
cout << "\n";
return 0;
}