DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Java (http://www.daniweb.com/forums/forum9.html)
-   -   inorder traverse (http://www.daniweb.com/forums/thread159896.html)

efus Nov 28th, 2008 3:30 pm
inorder traverse
 
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.

mahlerfive Nov 28th, 2008 4:05 pm
Re: inorder traverse
 
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;
}

quuba Nov 30th, 2008 1:25 pm
Re: inorder traverse
 
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


All times are GMT -4. The time now is 4:24 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC