I’ve got a binary tree that should only hold unique string values. Prior to entering a new string (which is done by the user), I need to recursively check the tree to see if the string already exists. Here’s the method I’ve come up with, but it’s only finding certain values (the root and the left ones I believe). Any tips on how to fix this are appreciated!
public static TreeNode wordExists(TreeNode root, String strInput){
if (root != null){
if (strInput.equals(root.dataItem))
{
return root;
}
if (root.left != null){
return wordExists (root.left, strInput);
}
if (root.right != null){
return wordExists (root.right, strInput);
}
}
return null;
}
When you navigate down each branch, you need to check the result before returning it. Otherwise, if the result is only in the right branch, but there are other, non-null values in the left, you’ll just return null, since it isn’t found in the left path.
So instead of
you might do something like
You can get away with the shortcut on the second recursion, since, if it fails, you’ll just be returning null anyway.