SortTree
クラスからTreePrinter
に(node.data)を送信してAツリーを印刷する方法を教えてください。印刷方法バイナリツリー?
import javax.swing.tree.TreeNode;
public class SortTree {
static Node root;
TreePrinter type =new TreePrinter();
class Node<A extends Comparable>{
int data;
Node left, right;
Node(int d) {
data = d;
left = null;
right = null;
}
}
Node sortedArrayToBST(int arr[], int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end)/2;
Node node = new Node(arr[mid]);
node.left = sortedArrayToBST(arr, start, mid - 1);
node.right = sortedArrayToBST(arr, mid + 1, end);
return node;
}
void preOrder(Node node) {
if (node == null) {
return;
}
//System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}
}
そして、これがTreePrinterクラスです:
import java.io.IOException;
import java.io.OutputStreamWriter;
public class TreePrinter {
public static class Node<T extends Comparable<T>> {
T value;
Node<T> left, right;
public void insertToTree(T v) {
if (value == null) {
value = v;
return;
}
if (v.compareTo(value) < 0) {
if (left == null) {
left = new Node<T>();
}
left.insertToTree(v);
} else {
if (right == null) {
right = new Node<T>();
}
right.insertToTree(v);
}
}
public void printTree(OutputStreamWriter out) throws IOException {
if (right != null) {
right.printTree(out, true, "");
}
printNodeValue(out);
if (left != null) {
left.printTree(out, false, "");
}
}
private void printNodeValue(OutputStreamWriter out) throws IOException {
if (value == null) {
out.write("<null>");
} else {
out.write(value.toString());
}
out.write('\n');
}
private void printTree(OutputStreamWriter out, boolean isRight, String indent) throws IOException {
if (right != null) {
right.printTree(out, true, indent + (isRight ? " " : " | "));
}
out.write(indent);
if (isRight) {
out.write("┌");
} else {
out.write("└");
}
out.write("────");
printNodeValue(out);
if (left != null) {
left.printTree(out, false, indent + (isRight ? " | " : " "));
}
}}}
行きがけとしてツリーを入力し(node.data)
treeprinter
にクラスを送信するために任意のヘルプをソートノード: