I have a binary tree which I would like to get printed out inorder.
Right now I have this recursice loop:

public void inorder()
    {
        if(leftChild != null )
            leftChild.inorder();

        System.out.print(" " + data);
        
        if(rightChild != null )
            rightChild.inorder();
    }

This get the right order printed. The problem is that I want this function to return a String with the right order.

Since you want to return a string, just save the string returned from each recursive call, plus the string of the data in the node you are looking at and add them all together:

public void inorder() {
    if(leftChild != null )
        String s1 = leftChild.inorder();

    String s2 = " " + data;
        
    if(rightChild != null )
        String s3 = rightChild.inorder();

    return s1 + s2 + s3;
}

Hello efus.
in inorder() function you have a line System.out.print(" " + data); Replace this static method with own.
Succesive collect nascent data in external buffer.
buffer can be placed in own singleton class.
0. Initialize external buffer;
---------------------------------
1. Invoke root.inorder();
2. Get external buffer as String
3. Clear external buffer

public void inorder() {
        if (leftChild != null) {
            leftChild.inorder();
        }
        Buffer.print(data.toString());
        System.out.print(" " + data);
        if (rightChild != null) {
            rightChild.inorder();
        }
    }

quuba

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.