recursion - Recursive toString binary tree output -
so want printout of binary tree read [a b c d e f] keep ending space , can't use substring remove it. best way approach this?
public string tostringinorder() { output = ""; output += printinorder(root); if(output.length() < 1) { return "[]"; } else { return "[" + output.substring(0, output.length() - 1) + "]"; } } private string printinorder(node current) { if(current != null) { printinorder(current.left); output += current.value + " "; printinorder(current.right); } return output; }
if concern removing space @ end replace:
return "[" + output.substring(0, output.length() - 1) + "]"; with:
return "[" + output.trim() + "]"; another approach might take filling list ordered values, , can have greater control of how format ordered values string.
Comments
Post a Comment