返回树的有序字符串 [英] Returning an inorder string of a Tree

查看:86
本文介绍了返回树的有序字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EDIT 如该线程中的建议,已通过使用StringBuilder来解决此问题.谢谢:D

EDIT This has been resolved by using StringBuilder as suggested in this thread. Thank you :D

你好,

我有一棵树,正在尝试按顺序返回内容的字符串.

I have a tree and am trying to return a String of the content in order.

我目前可以使用以下内容打印出树:

I can currently print out the tree with something like this:

    public void inOrder() {
        if (left != null) left.inOrder();
        System.out.print(content + " ");
        if (right != null) right.inOrder();
    }

但是我想做的是返回String(而不是在递归时打印出每个节点的内容),我不知道该怎么做.我尝试了以下代码的许多变体,但它仅返回在递归中找到的最后一个元素.

But what I want to do is return the String (rather than print out each nodes content while recursing) and I can't work out how to do it. I tried many variations of the code below, but it just returns the last element it finds in the recursion.

 public String inOrder(String string) {
        if (left != null) left.inOrder(string);
        string += content;
        if (right != null) right.inOrder(string);

        return string;
    }

推荐答案

字符串在Java中是不可变的.您不是将新的String连接到旧的String,而是创建新的String并使string变量指向它.结果是您有许多不相关的字符串,并且string变量在不同的时间点指向它们.

Strings are immutable in java. You are not concatenating new String to old one, you are creating new String and make string variable point to it. Result is that you have many unrelated Strings and string variable points to them in various points in time.

您需要将可变对象传递给您的函数,例如StringBuilder.该解决方案的另一个优点是效率更高,因为避免了不必要的对象分配.

You need to pass mutable object to your function such as StringBuilder. This solution have additional advantage that it's much more efficient because you are avoiding unnecessary Object allocations.

这篇关于返回树的有序字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆