在Java中搜索二叉树的所有节点
我正在尝试编写一个方法来搜索二叉树的所有节点以查找传递的值,并在找到该节点时返回该节点。我似乎无法找到正确的逻辑来搜索树的两边。这是我到目前为止所拥有的在Java中搜索二叉树的所有节点,java,search,binary-tree,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 th
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);
}
只有在没有左子树时才搜索右子树。您还希望在左子树中找不到字符串时对其进行搜索。这应该做到:
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;
}
@TwoMore-我不只是返回搜索左子树的结果,只要它不是
null
。我捕获搜索左子树的结果,如果找不到右子树,则搜索右子树。但是有时候,你的左子树是根,第一个if将返回null,对吗?它确实有效。非常感谢。这让我一整天都很难受。我想我是想想象一个更复杂的解决方案。@TwoMore-嗯…什么?我假设这是用locate(“Something”,root)
调用的。对不起,我的错误是,我假设currentNode被检查为null而不是root,算了吧