1
我有一个艰巨的任务需要你的帮助。按照一些规则逐级打印二叉树
我需要打印一个二叉树遵循此规则: 按级别打印级别,不使用矩阵; 必须从根目录打印,并且打印后永远不要编辑这些行; 该号码不能与其他任何列相同。 这是格式:
|----10----|
|--13--| 1---|
15 11 0
它是一个不AVL树。必须在任何大小的树上工作。
这是我到目前为止有:
public String printTree() {
if (getAltura() == -1) { //See if the tree is empty
return "Arvore Vazia";
}
if (getAltura() == 0) { //Check if only have one node in the tree;
return raiz.chave + "";
}
return printTree0();
}
private String printTree0() {
String arvore = ""; //String with the binary tree
//String linha = "";
int espaco = 0; //That was what I try to use to put the number under the "|" character
//int altura = 0;
Queue<Nodo> q = new LinkedList<>();
for (int i = 0; i <= getAltura(); i++) {
q.addAll(getNivel(i));
}
while (!q.isEmpty()) {
Nodo n = q.remove();
if (n.direito == null && n.esquerdo == null) {
for (int i = 0; i < espaco; i++) {
arvore += " ";
}
}
if (n.esquerdo != null) { //Check if this node has a left son.
int subarvores = tamanhoSubarvores(n.esquerdo); //Do the math to see how many ASCII character are need to put in this side of the tree.
for (int i = 0; i < subarvores; i++) {
arvore += " ";
espaco++;
}
arvore += "|";
for (int i = 0; i < subarvores; i++) {
arvore += "-";
}
}
arvore += n.chave;
if (n.direito != null) { //Check if this node has a right son.
int subarvores = tamanhoSubarvores(n.direito); //Do the math to see how many ASCII character are need to put in this side of the tree.
for (int i = 0; i < subarvores; i++) {
arvore += "-";
}
arvore += "|";
for (int i = 0; i < subarvores; i++) {
arvore += " ";
}
}
arvore += "\n";
}
return arvore;
}
private int tamanhoSubarvores(Nodo nodo) {
int size = 0;
for (Nodo n : getNivel(nodo.altura, nodo)) {
size += Integer.toString(n.chave).length();
}
return size;
}
谢谢。
如果你发布一些你的尝试,你会得到更多的运气。 – natario
什么是输入格式? – Cruncher
你问什么具体问题?你迄今为止做了什么工作?你有没有在http://stackoverflow.com/help/on-topic阅读stackoverflow介绍:*提问作业帮助的问题必须包括你迄今为解决问题所做的工作的总结,以及难以解决它。* –