I have a Binary Tree which has a word on each node.
In another Class I need to access the nodes one by one and then manipulate the words. What is the best way to access the nodes one by one from another class?
In my BinaryTree Class each node has a leftchild, rightchild and a value(String). I have three methods, printinorder, insert and findnode. The find node takes in a string and sees if that string is stored in any of the node values.
public void printInOrder(Node node) {
if (node != null) {
printInOrder(node.left);
System.out.println(node.value);
printInOrder(node.right);
}
I have another class and need to get at the nodes one by one but I am not sure whats the best way of doing it from another class. I am able to traverse the tree from within the class but not from a different class.
Read templatetypedef’s answer, which is a more efficient approach. The advantage of the approach I present is that it does not require any changes to your existing Node class, and uses the same pattern you’ve already used for PrintInOrder. It only relies upon public properties of the Node class, so should be useable from a separate class.
I didn’t compile or test this, so there may be errors.