Skip to content

Conversation

@sunha20
Copy link
Contributor

@sunha20 sunha20 commented Jan 20, 2026

🚀 이슈 번호

Resolve: {#2319}

🧩 문제 해결

스스로 해결: ✅ / ❌

🔎 접근 과정

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

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

중위순회의 마지막 노드(= 가장 오른쪽 노드)를 찾음
재귀를 돌면서 트리를 탐색하는데, 재귀를 호출했을때(자식으로 이동), 그리고 빠져나왔을 때(부모로 이동) 모두 count를 해주다가, 마지막 노드에 도달하면 멈춘다.
+) 더 최적화 시키려면 재귀 대신 전체 노드 개수 기반으로 count를 계산해 구할 수 있다.

⏱️ 시간 복잡도

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

  • Big-O 표기법: O(N)
  • 이유:
    재귀: N번당 오른쪽 왼쪽 탐색 OR 트리 모든 간선을 2번씩 방문(왕복)
    마지막 노드 찾기: 최적의 경우 logN이지만, 최악의 경우 N

💻 구현 코드

import java.io.*;

public class BOJ22856_트리순회 {

    static class Node {
        int left, right;

        void set(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }

    static int N, cnt, endNode;
    static Node[] tree;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());

        String[] temp;
        tree = new Node[N+1];
        int now;
        for (int n=0; n<N; n++){
            temp = br.readLine().split(" ");
            now = Integer.parseInt(temp[0]);

            tree[now] = new Node();
            tree[now].set(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]));
        }

        endNode = 1;
        while (tree[endNode].right != -1) {
            endNode = tree[endNode].right;
        }

        travel(1);
    }

    static void travel(int now) {
        cnt++;

        if (tree[now].left > 0) {
            travel(tree[now].left);
            cnt++;
        }

        if (tree[now].right > 0) {
            travel(tree[now].right);
            cnt++;
        }

        if (now == endNode) {
            System.out.println(cnt - 1); // 시작점 카운트(1) 제외하고 출력
        }

    }
}

@sunha20 sunha20 self-assigned this Jan 20, 2026
@sunha20 sunha20 linked an issue Jan 20, 2026 that may be closed by this pull request
@sunha20 sunha20 added the 트리 label Jan 20, 2026
@sunha20 sunha20 merged commit bb48e9d into main Jan 30, 2026
@sunha20 sunha20 deleted the sunha/2319/2 branch January 30, 2026 10:42
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