-
[BOJ] 5639 이진 검색 트리PS/BOJ 2022. 7. 18. 21:41
https://www.acmicpc.net/problem/5639
5639번: 이진 검색 트리
트리를 전위 순회한 결과가 주어진다. 노드에 들어있는 키의 값은 106보다 작은 양의 정수이다. 모든 값은 한 줄에 하나씩 주어지며, 노드의 수는 10,000개 이하이다. 같은 키를 가지는 노드는 없다
www.acmicpc.net
알고리즘: 트리 순회, 재귀
트리의 전위순회를 후위순회로 바꾸면 AC
좌노드 방문 -> 우노드 방문 -> 방문할 곳이 없으면 자기 자신 출력
구간을 [l, r]로 잡아주고,
왼쪽 자식을 탐색할 때: [l, 부모 노드 값)
오른쪽 자식을 탐색할 때: (부모 노드 값, r]
로 구간이 바뀐다는 이진 트리의 특성을 이용하여 재귀함수 구현
더보기This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#include <iostream> #include <algorithm> using namespace std; int inOrder[10002], idx, N; void sol(int l, int r){ int cur = inOrder[idx]; idx++; if (inOrder[idx] < cur && inOrder[idx] > l){ sol(l, cur); } if (inOrder[idx] > cur && inOrder[idx] < r){ sol(cur, r); } printf("%d\n", cur); } int main(){ ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); while (cin >> inOrder[N++]); sol(0, 1e7); } 'PS > BOJ' 카테고리의 다른 글
[BOJ] 13172 Σ (0) 2022.07.18 [BOJ] 단계별로 풀어보기 - 최단 경로 (0) 2021.06.15 [BOJ] 수열과 쿼리 13 (0) 2020.10.23 [BOJ] 13545 수열과 쿼리 0, 13550 수열과 쿼리 7 (0) 2020.10.23 [BOJ] 13546 수열과 쿼리 4 (0) 2020.10.22