Search code examples
javastringdata-structurestreepreorder

Returning a String of values from a tree


Ok so i want to traverse a tree with inorder, preorder and postorder. I got the right algorithms for traversing the tree but i need to return the String in the Form of "Node1 Node2 Node3" but i have "Node1Node2Node3". Here is my code for the preorder:

public String PreOrder() {
        /* TODO: Implement */
        StringBuilder string = new StringBuilder();
        preorderRecursive(string, root);
        return string.toString();
    }
    public StringBuilder preorderRecursive(StringBuilder string, Node current){
        if (current != null) {
        string.append(current.key);
        preorderRecursive(string, current.left);
        preorderRecursive(string, current.right);
        }
        return string;
    }

and i get the error org.junit.ComparisonFailure: expected:<3[ 1 2 8 4 5 7 9 ]10> but was:<3[1284579]10>


Solution

  • just add a space to the stringBuilder,

    if (current != null) {
       string.append(current.key).append(" ");
       ...