Searching all nodes of a binary tree in Java
binary-tree, java, search
Solution
You are only searching the right subtree when there is no left subtree. You also want to search it when the string was not found in the left subtree. This should do it:
private Node locate(String p, Node famTree)
{
Node result = null;
if (famTree == null)
return null;
if (famTree.value.equals(p))
return famTree;
if (famTree.left != null)
result = locate(p,famTree.left);
if (result == null)
result = locate(p,famTree.right);
return result;
}
Problem
I am trying to write a method to search all nodes of a binary tree for a passed value and return the node when found. I cannot seem to get the logic right to search both sides of the tree. Here is what I have so far. ``` private Node locate(String p, Node famTree) { if (root == null)//If tree empty return null; return null; if (famTree.value.equals(p)) //If leaf contains the passed parent value the boolean becomes true. return famTree; if (famTree.left != null) return locate(p,famTree.left); else return locate(p,famTree.right); } ```