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

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파

www.acmicpc.net




문제 풀이(코드)
import java.util.Scanner;
import java.util.ArrayList;

public class Main {
    public static void printPath(ArrayList<Integer> path) {
        for (int i = 0; i < path.size(); i++) {
            char cur = (char)(path.get(i) + 'A');
            System.out.print(cur);
        }
    }

    public static void preorder(int[][] tree, int row, ArrayList<Integer> path) {
        // 현재 노드 방문 처리
        path.add(tree[row][0]);
        // 왼쪽 노드로 이동
        if (tree[row][1] != -1) preorder(tree, tree[row][1], path);
        // 오른쪽 노드로 이동
        if (tree[row][2] != -1) preorder(tree, tree[row][2], path);
    }

    public static void inorder(int[][] tree, int row, ArrayList<Integer> path) {
        // 왼쪽 노드로 이동
        if (tree[row][1] != -1) inorder(tree, tree[row][1], path);
        // 현재 노드 방문 처리
        path.add(tree[row][0]);
        // 오른쪽 노드로 이동
        if (tree[row][2] != -1) inorder(tree, tree[row][2], path);
    }

    public static void postorder(int[][] tree, int row, ArrayList<Integer> path) {
        // 왼쪽 노드로 이동
        if (tree[row][1] != -1) postorder(tree, tree[row][1], path);
        // 오른쪽 노드로 이동
        if (tree[row][2] != -1) postorder(tree, tree[row][2], path);
        // 현재 노드 방문 처리
        path.add(tree[row][0]);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] tree = new int[n][3];

        for (int i = 0; i < n; i++) {
            int row = (int)(sc.next().charAt(0) - 'A');
            tree[row][0] = row;

            int left, right;
            for (int j = 1; j <= 2; j++) {
                char cur = sc.next().charAt(0);
                if (cur == '.') tree[row][j] = -1;
                else tree[row][j] = (int)(cur - 'A');
            }
        }

        ArrayList<Integer> preorderPath = new ArrayList<Integer>();
        preorder(tree, 0, preorderPath);

        ArrayList<Integer> inorderPath = new ArrayList<Integer>();
        inorder(tree, 0, inorderPath);

        ArrayList<Integer> postorderPath = new ArrayList<Integer>();
        postorder(tree, 0, postorderPath);

        printPath(preorderPath);
        System.out.println();
        printPath(inorderPath);
        System.out.println();
        printPath(postorderPath);
        System.out.println();
        
        sc.close();
    }
}

+ Recent posts