首页 > 解决方案 > 如何在 Java 中打印二叉树?

问题描述

public class BinaryNode<T> {

    protected T data;
    protected BinaryNode<T> left;
    protected BinaryNode<T> right;

    public BinaryNode(T element) {
        if (element == null)
            throw new IllegalArgumentException();
        this.data = element;
        left = null;
        right = null;
    }

    public int height() {
        int leftH = -1, rightH = -1;
        if (left != null)
            leftH = left.height();
        if (right != null)
            rightH = right.height();
        return Math.max(leftH, rightH) + 1;
    }

    public int size() {
        int leftS = 0, rightS = 0;
        if (left != null)
            leftS = left.size();
        if (right != null)
            rightS = right.size();
        return leftS + rightS + 1;
    }

    private String spaces(int count){
        String spaces="";
        while(count>0){
            spaces=spaces+"  ";
            count=count-1;
        }
        return spaces;
    }

    public String toString(){
        String str="";
        if(left!=null)
            str=str+spaces(left.height())+left.toString(); //left
        str=str+spaces(left.height()-1)+data.toString()+"\n";//root
        if(right!=null)
            str=str+spaces(right.height())+right.toString();//right
        return str;
    }
}

我需要在 BinaryNode 类中构建 toString 函数。该方法有效,因此如果我们打印它返回的字符串,我们将在树中的每个顶点得到一个打印行。在这一行中,将出现 2*d 个空格,其中 d 是树中顶点的深度,然后将打印有关顶点的信息(在同一行中)。例如对于以下 BinarySearchTree(BinarySearchTree 中的示例,因此更容易理解它需要如何打印):

    BinarySearchTree t4 = new BinarySearchTree(c);
    t4.insert(8);
    t4.insert(7);
    t4.insert(6);
    t4.insert(5);
    t4.insert(4);
    t4.insert(3);
    t4.insert(2);
    t4.insert(1);
    System.out.println("----------t4:----------\n" + t4);

toString 需要打印:

----------t4:----------

              1

            2

          3

        4

      5

    6

  7

8

我在上面写了我创建的代码但它不起作用,问题是我知道它为什么不起作用但我不知道如何修复它。基本上,我不知道该怎么做。
感谢任何帮助。

标签: javaalgorithmcomputer-science

解决方案


为有需要的人提供解决方案:

private String spaces(int count){
    String spaces="";
    while(count>0){
        spaces=spaces+"  ";
        count=count-1;
    }
    return spaces;
}

private String toString(int depth){
    String str="";
    if(left!=null)
    {
        str=str+left.toString(depth+1);
    }
    str=str+spaces(depth)+data.toString()+"\n";
    if(right!=null)
    {
        str=str+right.toString(depth+1);
    }
    return str;
}

private String toString(String str){
    if(left!=null)
        str=str+left.toString("  ");
    str=str+data.toString()+"\n";
    if(right!=null)
        str=str+right.toString("  ");
    return str;
}

推荐阅读