[백준 - 1991] 트리 순회

문제링크

import java.io.BufferedWriter

data class Node(val alphabet: Char, var left: Node? = null, var right: Node? = null)

fun main() {
    val bufferedReader = System.`in`.bufferedReader()
    val bufferedWriter = System.out.bufferedWriter()

    val n = bufferedReader.readLine().toInt()
    val nodes = createNodes(n)
    repeat(n) {
        val inputs = bufferedReader
            .readLine()
            .split(" ")
            .map { it.single() }
        val nodeIndex = inputs[0].code - 65
        if (inputs[1] != '.') {
            nodes[nodeIndex].left = nodes[inputs[1].code - 65]
        }
        if (inputs[2] != '.') {
            nodes[nodeIndex].right = nodes[inputs[2].code - 65]
        }
    }

    preOrder(nodes[0], bufferedWriter)
    bufferedWriter.write("\n")
    inOrder(nodes[0], bufferedWriter)
    bufferedWriter.write("\n")
    postOrder(nodes[0], bufferedWriter)

    bufferedReader.close()
    bufferedWriter.close()
}

fun createNodes(n: Int): List<Node> {
    val nodes = mutableListOf<Node>()
    repeat(n) {
        nodes.add(Node((it + 65).toChar()))
    }
    return nodes
}

fun preOrder(root: Node?, bufferedWriter: BufferedWriter) {
    root ?: return

    bufferedWriter.write("${root.alphabet}")
    preOrder(root.left, bufferedWriter)
    preOrder(root.right, bufferedWriter)
}

fun inOrder(root: Node?, bufferedWriter: BufferedWriter) {
    root ?: return

    inOrder(root.left, bufferedWriter)
    bufferedWriter.write("${root.alphabet}")
    inOrder(root.right, bufferedWriter)
}

fun postOrder(root: Node?, bufferedWriter: BufferedWriter) {
    root ?: return

    postOrder(root.left, bufferedWriter)
    postOrder(root.right, bufferedWriter)
    bufferedWriter.write("${root.alphabet}")
}

주석 없는 코드를 만들기 위해 노력하는 개발자입니다.

혹시라도 의도가 분명하지 않아보이는 (이해가 되지 않는) 코드가 있으시다면 편하게 답변 달아주시면 정말 감사하겠습니다.

좋은 웹페이지 즐겨찾기