[kotlin] 이진 트리(Binary Tree)의 개념과 구현 방법

이진 트리(Binary Tree)는 각 노드가 최대 두 개의 자식을 가지는 트리 구조입니다. 각 노드는 왼쪽 자식과 오른쪽 자식을 가리키는 링크를 가질 수 있습니다.

이진 트리의 구조

이진 트리의 각 노드는 데이터와 왼쪽 자식 노드, 오른쪽 자식 노드를 가리키는 링크를 포함합니다.

class BinaryTreeNode(val data: Int) {
    var left: BinaryTreeNode? = null
    var right: BinaryTreeNode? = null
}

이진 트리 구현하기

다음은 Kotlin으로 간단한 이진 트리를 구현하는 예제 코드입니다.

class BinaryTree {
    var root: BinaryTreeNode? = null

    fun insert(data: Int) {
        root = insertRecursive(root, data)
    }

    private fun insertRecursive(node: BinaryTreeNode?, data: Int): BinaryTreeNode {
        if (node == null) {
            return BinaryTreeNode(data)
        }

        if (data < node.data) {
            node.left = insertRecursive(node.left, data)
        } else if (data > node.data) {
            node.right = insertRecursive(node.right, data)
        }

        return node
    }
}

결론

Kotlin을 사용하여 간단한 이진 트리를 구현하는 방법을 살펴보았습니다. 이진 트리는 여러 분야에서 널리 사용되며, 다양한 알고리즘과 데이터 구조에서 중요한 역할을 합니다.

이러한 구조를 이해하고 구현하는 것은 개발자로서 기본적인 지식이 될 것입니다.

참고 자료: Kotlin Data Structures and Algorithms