[백준 5639번 C/C++] 이진 검색 트리

 

 

https://www.acmicpc.net/problem/5639

 

5639번: 이진 검색 트리

트리를 전위 순회한 결과가 주어진다. 노드에 들어있는 키의 값은 106보다 작은 양의 정수이다. 모든 값은 한 줄에 하나씩 주어지며, 노드의 수는 10,000개 이하이다. 같은 키를 가지는 노드는 없다

www.acmicpc.net


 

해결전략

 

깊이 우선 탐색 DFS

트리 후위 순회

 


 

정답 코드

 

#include <iostream>
#include <vector>
using namespace std;

vector<int> v;

void DFS(int start, int end)
{
	if (start >= end) {
		return;
	}
	if (start == end - 1) {
		cout << v[start] << "\n";
		return;
	}

	int idx = start + 1;
	while (idx < end)
	{
		if (v[start] < v[idx]) break;

		idx++;
	}

	DFS(start+1, idx);
	DFS(idx, end);
	cout << v[start] << "\n";
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
 
	int input;
	while (cin >> input){
		v.push_back(input);
	}
	int n = v.size();

	DFS(0, n);

	return 0;
}