2015-11-03 54 views
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; 
} 

谢谢。

+2

如果你发布一些你的尝试,你会得到更多的运气。 – natario

+1

什么是输入格式? – Cruncher

+1

你问什么具体问题?你迄今为止做了什么工作?你有没有在http://stackoverflow.com/help/on-topic阅读stackoverflow介绍:*提问作业帮助的问题必须包括你迄今为解决问题所做的工作的总结,以及难以解决它。* –

回答

1

你正在做的事叫做Breadth First Search。鉴于AVL tree仅在添加或移除元素期间与正常的Binary Search Tree不同,因此应适用上面wiki链接中列出的BF-Search的算法逻辑。

+0

谢谢,这有助于很多。到目前为止,我只打印第一层,并在树上进一步深入。 –