[AVAで実施[ツリー]


ノード表示左サブアイテム-右兄弟表示(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