[20250714] BOJ / G1 / 트리의 순회 / 이강현 #463
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🧷 문제 링크
https://www.acmicpc.net/problem/2263
🧭 풀이 시간
60분
👀 체감 난이도
✏️ 문제 설명
이진 트리에 중복없는 값들이 저장되어 있다.
inorder와 postorder가 주어질때, preorder를 출력하라.
🔍 풀이 방법
분할 정복

inorder는 왼쪽 서브트리 탐색, 출력, 오른쪽 서브트리 탐색
postorder는 왼쪽 서브트리 탐색, 오른쪽 서브트리 탐색, 출력
따라서 postorder의 맨 마지막 값이 전체 트리의 root이다.
트리의 root를 찾고 이 값이 inorder의 어디에 있는지 알면 그 값을 기준으로 해당 트리의 왼쪽 서브트리와 오른쪽 서브트리의 범위를 특정지을 수 있다.
왼쪽 서브트리의 크기와 오른쪽 서브트리의 크기를 알면 postorder에서도 서브트리들의 범위를 특정지을 수 있다.
이를 반복해가며 root를 찾을 때마다 출력하면 preorder를 구할 수 있다.
⏳ 회고
postorder의 맨 마지막이 트리의 root라는 힌트를 통해 해결할 수 있었다.
역으로 preorder가 주어진다면 맨 앞이 root라는 힌트를 통해 응용문제를 해결할 수 있을 것 같다.