[java] 자바로 트리 알고리즘 구현하기

트리는 계층적인 데이터 구조를 나타내는 데 사용되는 중요한 자료 구조입니다. 이번 글에서는 자바를 사용하여 트리 알고리즘을 구현하는 방법에 대해 알아보겠습니다.

트리 알고리즘 구현

이진 트리 구현하기

이진 트리는 각 노드가 최대 두 개의 자식을 가질 수 있는 트리 구조입니다. 아래는 이진 트리를 자바로 구현하는 간단한 예제 코드입니다.

class Node {
    int data;
    Node left;
    Node right;

    public Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class BinaryTree {
    Node root;

    public BinaryTree() {
        root = null;
    }

    // 이진 트리에 노드 추가하기
    public void insert(int data) {
        root = insertRec(root, data);
    }

    private Node insertRec(Node root, int data) {
        if (root == null) {
            root = new Node(data);
            return root;
        }

        if (data < root.data) {
            root.left = insertRec(root.left, data);
        } else if (data > root.data) {
            root.right = insertRec(root.right, data);
        }

        return root;
    }
}

이진 탐색 트리 구현하기

이진 탐색 트리는 이진 트리 중에서도 좌측 서브트리의 모든 노드가 특정 노드보다 작고 우측 서브트리의 모든 노드가 특정 노드보다 큰 조건을 가지는 트리 구조입니다.

class BinarySearchTree {
    Node root;

    public BinarySearchTree() {
        root = null;
    }

    // 이진 탐색 트리에 노드 추가하기
    public void insert(int data) {
        root = insertRec(root, data);
    }

    private Node insertRec(Node root, int data) {
        if (root == null) {
            root = new Node(data);
            return root;
        }

        if (data < root.data) {
            root.left = insertRec(root.left, data);
        } else if (data > root.data) {
            root.right = insertRec(root.right, data);
        }

        return root;
    }
}

마치며

이러한 방법을 사용하여 자바로 간단한 트리 알고리즘을 구현할 수 있습니다. 트리는 데이터 구조 및 알고리즘에서 다양한 용도로 활용되며, 추가적인 기능을 구현하여 더 다양한 애플리케이션에 활용할 수 있습니다.

참고문헌: