본문 바로가기

Java SE/Tree example

Java Tree example

자바(Java) 트리(Tree) 구현 예제


아래의 코드에 포함된 main(), printTree() 메소드는 디버깅 용도와 사용법을 안내하기 위해 추가한 것이므로 실제 사용시에는 불필요함

package org.kdea.minmax; import java.util.*; public class Node <T> { private T data; private Node<T> parent; private List<Node<T>> children = new ArrayList(); /** * 이 클래스의 사용법을 안내할 목적으로 추가된 main() */ public static void main(String[] args) { Node<String> root = new Node(); root.setData("가"); Node<String> childA = new Node(); childA.setData("A"); root.addChild(childA); Node<String>childB = new Node(); childB.setData("B"); root.addChild(childB); Node<String>childC = new Node(); childC.setData("C"); root.addChild(childC); Node<String> childOne = new Node(); childOne.setData("ONE"); childA.addChild(childOne); Node<String> childTwo = new Node(); childTwo.setData("TWO"); childA.addChild(childTwo); printTree(root, 0); } /** * Use for debugging. prints all nodes from root to leaves * @param node 콘솔화면에 출력할 root node의 참조 * @param level 콘솔화면에 출력할 차수, 처음 호출시 반드시 0을 전달하세요 */ private static void printTree(Node<String> node, int level){ int indent = level++; String tabs = ""; for(int i=0;i<indent;i++) { tabs+="\t"; } System.out.println(tabs+node.getData()); List<Node<String>> children = node.getChildren(); if(children.size()==0) { return; } for(int i=0;i<children.size();i++) { Node<String> child = children.get(i); printTree(child, level); } } public void addChild(Node<T> child) { child.setParent(this); getChildren().add(child); } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node<T> getParent() { return parent; } public void setParent(Node<T> parent) { this.parent = parent; } public List<Node<T>> getChildren() { return children; } public void setChildren(List<Node<T>> children) { this.children = children; } }


위의 코드를 실행하면 다음과 같은 Tree의 계층구조가 표현되어 출력됨

A

ONE

TWO

B

C