Funktion um Bäume in der Console darzustellen

phm
Neuling
Neuling
Beiträge: 8
Registriert: 6. Mai 2009 18:55

Funktion um Bäume in der Console darzustellen

Beitrag von phm »

Hallo alle zusammen!

Ich habe eine Funktion geschrieben, um einen Baum darzustellen. Ich hoffe das hilft euch. Um sie aufzurufen: TreeDisplayer.display(node)


TreeDisplayer.java:

import java.util.ArrayList;
import java.util.LinkedList;

public class TreeDisplayer {
static final int MIN_SPACE = 2;
static final int NAME_LENGTH = 4;
static final int MAX_LEVEL = 5; // max_height - 1
static final char completeChar = '-';

static int[] interSpaces = new int[MAX_LEVEL+1];
static int[] tabLengths = new int[MAX_LEVEL+1];
static int p2h;

private static void computeSpaces() {
int i = 0;
int p2i = 1; // 2^i
for (int level=maxLevel; level>=0; level--) {
interSpaces[level] = p2i * (NAME_LENGTH + MIN_SPACE) - NAME_LENGTH;
tabLengths[level] = ((p2i - 1) * (NAME_LENGTH + MIN_SPACE)) / 2;
i++;
p2i *= 2;
}
p2h = p2i/2;
}

static class NodeToDisplay {
public CounterIntelligence.Tree node;
public int level;
public int hrzPos;

public NodeToDisplay(CounterIntelligence.Tree n, int x, int y) {
node = n;
level = x;
hrzPos = y;
}
}

static LinkedList<NodeToDisplay> queueBFS = new LinkedList<NodeToDisplay>();
static int currentLevel;
static int nextHrzPos;
static int maxLevel;

static private String displayOneNode(String name) {
String str = "";
int nameLength = name.length();
int completeNameBefore = (NAME_LENGTH - nameLength) / 2;
int completeNameAfter = NAME_LENGTH - (completeNameBefore + nameLength);

for (int i=0; i<completeNameBefore; i++) str = str + completeChar;
str = str + name;
for (int i=0; i<completeNameAfter; i++) str = str + completeChar;
for (int i=0; i<interSpaces[currentLevel]; i++) str = str + " ";
return str;
}

static public void display(CounterIntelligence.Tree root) {
currentLevel = -1;
maxLevel = root.height-1;
if (maxLevel > MAX_LEVEL) maxLevel = MAX_LEVEL;
computeSpaces();

queueBFS.addLast(new NodeToDisplay(root,0,0));
while (!queueBFS.isEmpty()) {
NodeToDisplay ntd = queueBFS.removeFirst();

String str="";
if (ntd.level > currentLevel) {
// update space values
currentLevel = ntd.level;
nextHrzPos = 0;
int tabLength = tabLengths[currentLevel];
for (int i=0; i<maxLevel; i+=2) str = str + "\n";
for (int i=0; i<tabLength; i++) str = str + " ";
}

for (int i=nextHrzPos; i<ntd.hrzPos; i++) str = str + displayOneNode("");
str = str + displayOneNode(ntd.node.agent);
System.out.print(str);

if (ntd.node.left != null)
queueBFS.addLast(new NodeToDisplay(ntd.node.left,ntd.level+1,ntd.hrzPos*2));
if (ntd.node.right != null)
queueBFS.addLast(new NodeToDisplay(ntd.node.right,ntd.level+1,ntd.hrzPos*2+1));
nextHrzPos = ntd.hrzPos + 1;
}

String str="";
for (int i=nextHrzPos; i<p2h; i++) str = str + displayOneNode("");
System.out.println(str);
}
}

Zurück zu „Archiv“