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 | 29 | 30 | 31 |
Tags
- Lv.1
- 운영체제
- 쿠쉬쿠쉬
- 파이썬
- Java
- BruteForceSearch
- 해시
- C
- 동적계획법
- C++
- 이분그래프판별
- Python
- 프로그래머스
- 2색칠하기
- hash
- 고득점Kit
- 단지번호붙이기
- 알고리즘
- 코딩테스트
- BFS
- Lv.2
- LV.3
- 코테준비
- 그래프
- Algorithm
- 코딩테스트준비
- OS
- 문제풀이
- 면접질문
Archives
- Today
- Total
쿠쿠의기록
13. 트리 순회 결과 출력하기 본문
문제
루트가 0인 이진트리가 주어질 때, 이를 전위순회, 중위순회, 후위순회한 결과를 각각 출력하는 프로그램을 작성하시오.
입력
첫 번째 줄에 트리의 노드 개수 n이 주어진다. ( 1 ≤ n ≤ 100 ) 두 번째 줄부터 트리의 정보가 주어진다. 각 줄은 3개의 숫자 a, b, c로 이루어지며, 그 의미는 노드 a의 왼쪽 자식노드가 b, 오른쪽 자식노드가 c라는 뜻이다. 자식노드가 존재하지 않을 경우에는 -1이 주어진다.
출력
첫 번째 줄에 전위순회, 두 번째 줄에 중위순회, 세 번째 줄에 후위순회를 한 결과를 출력한다.
예제 입력
6
0 1 2
1 3 4
2 -1 5
3 -1 -1
4 -1 -1
5 -1 -1
예제 출력
0 1 3 4 2 5
3 1 4 0 2 5
3 4 1 5 2 0
#include <stdio.h>
const int MAX = 100;
struct Tree{
int left;
int right;
};
Tree tree[MAX];
void preorder(int x){
if(tree[x].left == -1 && tree[x].right==-1){
printf("%d ",x);
}else{
printf("%d ",x);
if(tree[x].left != -1){
preorder(tree[x].left);
}
if(tree[x].right != -1){
preorder(tree[x].right);
}
}
}
void inorder(int x){
if(tree[x].left == -1 && tree[x].right==-1){
printf("%d ",x);
}else{
if(tree[x].left != -1){
inorder(tree[x].left);
}
printf("%d ",x);
if(tree[x].right != -1){
inorder(tree[x].right);
}
}
}
void postorder(int x){
if(tree[x].left == -1 && tree[x].right==-1){
printf("%d ",x);
}else{
if(tree[x].left != -1){
postorder(tree[x].left);
}
if(tree[x].right != -1){
postorder(tree[x].right);
}
printf("%d ",x);
}
}
int main() {
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d %d",&tree[i],&tree[i].left,&tree[i].right);
}
preorder(0);
puts("");
inorder(0);
puts("");
postorder(0);
return 0;
}
'알고리즘 > L11~13 자료구조' 카테고리의 다른 글
13. 트리의 높이. 트리의 높이 (0) | 2021.04.09 |
---|---|
13.공통 조상 찾기 (0) | 2021.04.06 |
12.큐 - 원형큐 구현하기 (0) | 2021.02.23 |
12. 큐 - 큐 구현하기 (0) | 2021.02.23 |
11. 스택 - 탑 (0) | 2021.02.23 |