java 用Java搜索二叉树的所有节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15941204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Searching all nodes of a binary tree in Java
提问by BigGrizzle
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);
}
回答by Ted Hopp
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;
}