I believe my inOrderTraverseTree() method puts the tree in order but I'm not sure how to go about actually printing it in order like that. Any suggestions? And why does the method not print them out in order as it is?
Thanks, Zach
public class Tree
{
Node root;
public static void main(String[] args){
Tree t = new Tree();
t.addNode("hey");
t.addNode("fghjk");
t.addNode("aaaaaa");
t.addNode("zzzzzz");
t.addNode("egh");
t.addNode("rrrrrr");
t.inOrderTraverseTree(t.root);
}
public void displayTree(){
Node link = root;
while(link != null){
}
}
public void addNode(String line){
//Create a new Node and initialize it
Node newNode = new Node(line);
//If there is no root this becomes root
if(root == null){
root = newNode;
} else {
//Set root as the Node we will start
//with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while(true){
// root is the top parent so we start there
parent = focusNode;
//Check if the new Node should go on the left
//side of the parent node
if(line.compareTo(focusNode.line) == -1){
focusNode = focusNode.leftChild;
//If the left child has no children
if(focusNode == null){
parent.leftChild = newNode;
return; //All Done
}
} else { // If we get here put the node on the right
focusNode = focusNode.rightChild;
//If the right child has no children
if(focusNode == null){
//then place the node on the right of it
parent.rightChild = newNode;
return; //All Done
}
}
}
}
}
public void inOrderTraverseTree(Node focusNode)
{
if(focusNode != null){
//traverse the left node
inOrderTraverseTree(focusNode.leftChild);
//Visit the currently focused on node
System.out.println(focusNode);
//Traverse the right node
inOrderTraverseTree(focusNode.rightChild);
}
}
class Node {
String line;
Node leftChild;
Node rightChild;
Node(String line){
this.line = line;
}
//this method overrides toString in Object class
public String toString(){
return line;
}
}
}