簡體   English   中英

如何在Java中打印BinaryTree?

[英]How to print BinaryTree in 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

我在上面創建的代碼上寫了代碼,但是它不起作用,問題是我知道為什么它不起作用,但是我不知道如何解決它。 基本上,我不知道這樣做。
感謝任何幫助。

為需要它的人提供了解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM