按照一些规则逐级打印二叉树

时间:2015-11-03 16:49:40

标签: java binary-search-tree

我有一项艰巨的任务,需要你的帮助。

我需要按照以下规则打印二叉树: 不使用矩阵逐级打印; 必须从根打印,你永远不应该在打印后编辑行; 该数字不能与任何其他列相同。 格式如下:

              |----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;
}

谢谢。

1 个答案:

答案 0 :(得分:1)

您要做的事情称为Breadth First Search。假设在添加或删除元素期间AVL tree仅与普通Binary Search Tree不同,则应用上面wiki链接中列出的BF-Search的算法逻辑。