[1231. [S/W 문제해결 기본] 9일차 - 중위순회]

문제


쿼리를 입력받아 트리를 생성하고 트리에서 중위순회를 하면 되는 문제이다. 이진트리이므로 배열에 index 를 사용해도 됐지만 구조체를 하나 만들어 부모자식을 입력해주었다.

실수


코드


import java.util.Scanner;

class Tree {
    public char data;
    public int left;
    public int right;

    public Tree(char data) {
        this.data = data;
        this.left = -1;
        this.right = -1;
    }
}

class Solution {

    final int MAX_NODE = 10000;

    Tree[] tree = new Tree[MAX_NODE];
    int treeCnt = 0;

    static void printTree(Tree[] tree, int index) {
        if (tree[index].left != -1) {
            printTree(tree, tree[index].left);
            System.out.print(tree[index].data);
            if (tree[index].right != -1) {
                printTree(tree, tree[index].right);
            }
        } else {
            System.out.print(tree[index].data);
        }
    }

    public static void main(String args[]) throws Exception {

        Scanner sc = new Scanner(System.in);
        int T = 10;

        int N, index;
        String line;
        String[] str;
        for (int test_case = 1; test_case <= T; test_case++) {
            N = sc.nextInt();
            sc.nextLine();
            /////////////////////////////////////////////////////////////////////////////////////////////
            Tree[] tree = new Tree[N];
            for (int i = 0; i < N; i++) {
                line = sc.nextLine();
                str = line.split(" ");
                index = Integer.parseInt(str[0]) - 1;
                tree[index] = new Tree(str[1].charAt(0));
                if (str.length > 2) {
                    tree[index].left = Integer.parseInt(str[2]) - 1;
                    if (str.length > 3) {
                        tree[index].right = Integer.parseInt(str[3]) - 1;
                    }
                }
            }
            System.out.print("#" + test_case + " ");
            printTree(tree, 0);
            System.out.println();
            /////////////////////////////////////////////////////////////////////////////////////////////

        }
    }
}

업데이트:

댓글남기기