EDIT This has been resolved by using StringBuilder as suggested in this thread. Thank you :D
Hello,
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();
}
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;
}
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.
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.