在Java中搜索二叉树的所有节点

Big*_*zle 3 java search binary-tree

我正在尝试编写一种方法来搜索二叉树的所有节点以获取传递的值,并在找到时返回该节点.我似乎无法正确地搜索树的两侧.这是我到目前为止所拥有的.

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);

}
Run Code Online (Sandbox Code Playgroud)

Ted*_*opp 9

当没有左子树时,您只搜索正确的子树.您还希望在左子树中找不到字符串时搜索它.这应该这样做:

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;

}
Run Code Online (Sandbox Code Playgroud)