[트리] JAVA로 구현

nakkim·2022년 3월 22일
0

노드 표현 방식은 왼쪽 자식-오른쪽 형제 표현법(LCRS) 사용
트리 표현은 들여쓰기 표현법 사용

노드 선언

public class treeNode {
    public char data;
    public treeNode leftChild;
    public treeNode rightSibling;
}

노드 생성, 연결, 출력

public class treeMethod {

    public treeNode createNode(char data) {
        treeNode newNode = new treeNode();
        newNode.data = data;
        newNode.leftChild = null;
        newNode.rightSibling = null;

        return newNode;
    }

    public void addChildNode(treeNode parent, treeNode child) {
    	// 자식 노드 없으면 바로 추가
        if (parent.leftChild == null) {
            parent.leftChild = child;
            return;
        }
        treeNode currentNode = parent.leftChild;
        // 마지막 형제 노드의 오른쪽에 추가
        while (currentNode.rightSibling != null) currentNode = currentNode.rightSibling;
        currentNode.rightSibling = child;
    }

    // 들여쓰기 표현법 사용
    public void printTree(treeNode node, int depth) {

		// 깊이만큼 공백 출력
        for (int i = 0; i < depth; i++) System.out.print(" ");

        System.out.println(node.data);

        if (node.leftChild != null) printTree(node.leftChild, depth + 1);
        if (node.rightSibling != null) printTree(node.rightSibling, depth);
    }
}

테스트

public class treeTest {

    public static void main(String[] args) {
        treeMethod tm = new treeMethod();
        treeNode a = tm.createNode('a');
        treeNode b = tm.createNode('b');
        treeNode c = tm.createNode('c');
        treeNode d = tm.createNode('d');
        treeNode e = tm.createNode('e');
        tm.addChildNode(a, b);
        tm.addChildNode(a, c);
        tm.addChildNode(b, d);
        tm.addChildNode(b, e);
        tm.printTree(a, 0);
    }
}

출력
a
 b
  d
  e
 c
profile
nakkim.hashnode.dev로 이사합니다

0개의 댓글