I'm having an issue getting my binary tree to print as a String. My code is suppose to take a string of numbers and create a binary tree with it. Its then suppose to return the value from tree in order. I seem to be confusing my implementation but everything that I've looked up to try doesn't seem to work with my code. I'll post my different attempts, hopefully there's just something that I missed.
class Node
{
Node left, right;
Double value;
public Node()
{
value = null;
left = right = null;
}
public Node(Double item)
{
value = item;
left = right = null;
}
public String display() //This was my first attempt
{
/*This was my first attempt but it only gives me an infinite loop
while(value != null)
{
System.out.println(left.toString());
System.out.println(value.toString());
System.out.println(right.toString());
}
return null;
*/
/*This was the second attempt, but i can't implement it because it comes as different types
StringBuffer sb = new StringBuffer();
for(Double value:this) sb.append(value.toString());
return sb.toString();
*/
/* This was attempt 3, but it only prints the first node value
String result = "";
if(value != null)
{
left.toString();
result = " " + Double.toString(value);
right.toString();
}
return result;
*/
}
}
Node root;
public void insert(Double h)
{
root = insertNode(root, h);
}
public Node createNodeTree(String expression)
{
System.out.println("Expression is " + expression);
for(String i:expression.split("\\s", 0))
{
System.out.println("Current node is " + i);
insert(Double.parseDouble(i));
}
System.out.println("Tree Complete");
return root;
}
public Node insertNode(Node i, Double j)
{
System.out.println("Inside insertNode");
if( i == null )
{
i = new Node(j);
return i;
}
if(j < i.value)
i.left = insertNode(i.left, j);
else if(j > i.value)
i.right = insertNode(i.right, j);
return i;
}
Assuming that I call an expression with seven numbers like this
createNodeTree("2 3 7 4 8 6 1").display();
I want it to return as
1 2 3 4 6 7 8
Yet so far I've only been able to get it to return the last value the program reads
Please, any help with this would be appreciated!
Edit 1:
So after the suggestion, I created this method
public String display()
{
return (left == null && right == null && value != null) ? value.toString() :" " + left.toString() + " " + value + " " + right.toString();
}
But this seems to return what I think are reference values instead of the actual nodes left and right values
Please Help!