Java 二叉搜索树:递归 toString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20489834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:17:23  来源:igfitidea点击:

Binary Search Tree: Recursive toString

javarecursionbinary-tree

提问by user2810123

It only prints out one item. It is suppose to print the contents of the tree in ascending order

它只打印出一项。假设按升序打印树的内容

public String toString()
{
    return toString (_root);
}
private String toString(BSTnode root)
{
    if (root == null)
        return "";
    toString(root._left);
    toString(root._right);
    return root._data.toString();
}

回答by RamonBoza

How do you want to show them?

你想如何向他们展示?

You need to append the Strings, for example.

例如,您需要附加字符串。

private String toString(BSTnode root)
{
    StringBuilder builder = new StringBuilder();
    if (root == null)
        return "";
    builder.append(toString(root._left));
    builder.append(toString(root._right));
    return builder.append(root._data.toString()).toString();
}

or just use a concatenation on strings.

或者只是在字符串上使用连接。

private String toString(BSTnode root)
{
    String result = "";
    if (root == null)
        return "";
    result += toString(root._left);
    result += toString(root._right);
    result += root._data.toString()
    return result;
}

回答by Melvin

//Helper

public String toString(){
return "<" +toString(root) + ">";
}

//recursively printing out the nodes

public static String toString(Node r){
if(r==null)
return "";
else
return toString(r.left) + " " +r.value + " " +toString(r.right);
}

回答by pkm

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }

    // Helper

    public String toString() {
        return "<" + toString(this) + ">";
    }

    // recursively printing out the nodes

    public static String toString(TreeNode r) {
        if (r == null)
            return "";
        else
            return r.val + " " + toString(r.left) + " " + toString(r.right);
    }

}