Hey,
We were instructed to build a Node class and a BinaryTree class in java and do an in-order traverse on it. (Print out in order) I know that I am building my tree correctly (w/ pointers, etc.) because I can use System.out.println() to tell me. However, we were instructed to pass one string around and have all the nodes add their "info" to it, in this case a String that is a persons name. So I wrote this:
In my BinaryTree class where root is a Node:
public String toString()
{
String temp = "";
if(root != null)
{
temp = root.inOrder(temp);
}
else
temp = "";
return temp;
}
And my inOrder() method looks like this in my Node class:
public String inOrder(String s)
{
if(left != null)
left.inOrder(s);
s = s + "\n" + info;
if(right != null)
right.inOrder(s);
return s;
}
However, Im not sure as to why its only printing out the root's info? And not the rest!! BTW, he told me that is the correct algorithm for the inOrder traverse, I just wasnt passing the String parameter right...
FROM THE TEACHER:
"The way you are traversing the tree is fine. By that I mean you are moving from node to node through the tree correctly. Your problem comes from the way you are passing parameters. What you are trying to accomplish here is to create a String called "temp" in your Binary Tree class and then, as you "visit" each node, that node should append its "info" to the string. When you have visited all the nodes, the string is returned to the Binary tree object with all the info concatenated into that one string.
That means that that one string must be passed to each node and returned from each node. Notice that in your code for the "inOrder" method, you create a new empty string in that node, add the info for that node and then return it. It doesn't get passed on to the next node."
Any help??? Thanks alot! :)