inorder traverse

Reply

Join Date: Oct 2008
Posts: 11
Reputation: efus is an unknown quantity at this point 
Solved Threads: 0
efus's Avatar
efus efus is offline Offline
Newbie Poster

inorder traverse

 
0
  #1
Nov 28th, 2008
I have a binary tree which I would like to get printed out inorder.
Right now I have this recursice loop:
  1. public void inorder()
  2. {
  3. if(leftChild != null )
  4. leftChild.inorder();
  5.  
  6. System.out.print(" " + data);
  7.  
  8. if(rightChild != null )
  9. rightChild.inorder();
  10. }
This get the right order printed. The problem is that I want this function to return a String with the right order.
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 77
Reputation: mahlerfive is an unknown quantity at this point 
Solved Threads: 16
mahlerfive mahlerfive is offline Offline
Junior Poster in Training

Re: inorder traverse

 
0
  #2
Nov 28th, 2008
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:
  1. public void inorder() {
  2. if(leftChild != null )
  3. String s1 = leftChild.inorder();
  4.  
  5. String s2 = " " + data;
  6.  
  7. if(rightChild != null )
  8. String s3 = rightChild.inorder();
  9.  
  10. return s1 + s2 + s3;
  11. }
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 332
Reputation: quuba is on a distinguished road 
Solved Threads: 53
quuba quuba is offline Offline
Posting Whiz

Re: inorder traverse

 
0
  #3
Nov 30th, 2008
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
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC