Java学習–二分木(binary tree)クラスの定義と使い方

1.二分木クラスの定義
package org.tang.binarytree;

public class BinaryTree<T extends Comparable<T>> {
private Node<T> root;

public Node<T> getRoot() {
return root;
}

public void setRoot(Node<T> root) {
this.root = root;
}

public void addElement(T element){
if(element == null){
return;
}
Node<T> node = new Node<T>(element);
if(this.root == null){
this.root = node;
}else{
this.root.addChild(node);
}
}

public void printBinaryTree(){
if(this.root == null){
System.out.println(“can not print null object”);
return;
}
this.root.printNode();
}

private static class Node<E extends Comparable<E>>{
private E nodeData;
private Node<E> left;
private Node<E> right;
private Node(E nodeData){
this.nodeData = nodeData;
}

private void addChild(Node<E> child){
if(child == null){
return;
}
if(this.compareTo(child) >= 0){
if(this.left == null){
this.left = child;
}else{
this.left.addChild(child);
}
}else{
if(this.right == null){
this.right = child;
}else{
this.right.addChild(child);
}
}
}

private int compareTo(Node<E> node){
return this.nodeData.compareTo(node.nodeData);
}

private void printNode(){
if(this.left != null){
this.left.printNode();
}
System.out.println(this.nodeData.toString());
if(this.right != null){
this.right.printNode();
}
}
}
}
2.Mainプログラム
package org.tang.binarytree;
public class Client {
public static void main(String[] args){
BinaryTree<Integer> qtm = new BinaryTree<Integer>();
qtm.addElement(98);
qtm.addElement(42);
qtm.addElement(36);
qtm.addElement(1);
qtm.addElement(24);
qtm.addElement(-1);
qtm.printBinaryTree();

BinaryTree<String> yc2 = new BinaryTree<String>();
yc2.addElement(“b”);
yc2.addElement(“B”);
yc2.addElement(“y”);
yc2.addElement(“f”);
yc2.printBinaryTree();
}
}