Skip to content

Conversation

@alirz-pixel
Copy link
Member

🚀 이슈 번호

Resolve: {#2319}

🧩 문제 해결

스스로 해결:

🔎 접근 과정

문제 해결을 위한 접근 방식을 설명해주세요.

  • 🔹 어떤 알고리즘을 사용했는지: DFS
  • 🔹 어떤 방식으로 접근했는지

일단 DFS를 진행하여 중위순회의 끝을 구한다.

이후 DFS를 진행하되 "다시 부모로 돌아가는 길"을 생각하여 왼쪽 노드 / 오른쪽 노드를 stack에 삽입하면서 top도 같이 삽입해준다.
이렇게 하면 문제에서 원하는 유사 중위 순회가 완성이 된다.

종료 조건은 현재 노드를 기준으로 모든 자식 노드를 탐색하였으며, 중위 순회의 끝에 도달할 경우이다.

⏱️ 시간 복잡도

시간 복잡도 분석을 작성해주세요.
최악의 경우 수행 시간은 어느 정도인지 분석합니다.

  • Big-O 표기법: O(N)
  • 이유:

tree 순회는 노드의 개수 만큼 진행되기 때문이다.

💻 구현 코드

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int find_end_node(vector<pair<int, int>>& nodes) {
	int cur_top = 0;
	while (true) {
		// 1. 단 오른쪽으로 가기
		if (nodes[cur_top].second >= 0)
			cur_top = nodes[cur_top].second;
		else
			break;
	}
	return cur_top;
}

int dfs(vector<pair<int, int>> &nodes) {
	int end_node = find_end_node(nodes);
	//cout << end_node + 1 << "\n";

	vector<bool> visited(nodes.size());
	stack<int> st;
	st.push(0);

	int answer = 0;
	while (!st.empty()) {
		int top = st.top();
		st.pop();

		//cout << top + 1 << " ";
		answer++;

		bool is_inserted = false;

		if (nodes[top].second >= 0 && !visited[nodes[top].second]) {
			visited[nodes[top].second] = true;
			st.push(top);
			st.push(nodes[top].second);
			is_inserted = true;
		}

		if (nodes[top].first >= 0 && !visited[nodes[top].first]) {
			visited[nodes[top].first] = true;
			st.push(top);
			st.push(nodes[top].first);
			is_inserted = true;
		}

		if (!is_inserted) {
			if (top == end_node)
				break;
		}
	}
	return answer - 1;
}

int main() {
	int N;
	cin >> N;

	vector<pair<int, int>> nodes(N);
	for (int i = 0; i < N; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		a--; b--; c--;

		nodes[a] = { b, c };
	}

	cout << dfs(nodes);

	return 0;
}

@alirz-pixel alirz-pixel self-assigned this Jan 20, 2026
@alirz-pixel alirz-pixel linked an issue Jan 20, 2026 that may be closed by this pull request
@alirz-pixel alirz-pixel merged commit 8b9e163 into main Jan 25, 2026
1 check passed
@alirz-pixel alirz-pixel deleted the munhyeong/2319/2 branch January 25, 2026 11:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

260120 : 코딩테스트

2 participants