I am looking to search a binary tree to find a string stored in the nodes.
public void traverse (BinaryTreeNode root){
if (root.leftchild != null){
traverse (root.leftchild);
}
System.out.println(root.character);
if (root.rightchild != null){
traverse (root.rightchild);
}
}
This works perfectly fine and displays all the nodes in the tree. (The code was worked from code on another old stackoverflow question! My issue is how to compare root.character to the inputted string and if it matches break out of the recursion. If someone could drop some hints I would appreciate it.
public BinaryTreeNode traverse (BinaryTreeNode root, String inString){ // Each child of a tree is a root of its subtree.
if (root.character != null) {
if (root.character.equalsIgnoreCase(inString)) {
System.out.println("root.charcter: " + root.character + " char " + inString);
return root;
}
}
if (root.leftchild != null){
traverse (root.leftchild, inString);
}
if (root.rightchild != null){
traverse (root.rightchild, inString);
}
return null;
}
The code above seems to work, it returns the correct BinaryTreeNode however, I haven't worked out how to stop the recursion once the node is found and therefore it returns a null at the end aswell.