递归函数 return 错误 returns false
Recursive function return incorrectly returns false
我目前正在编写一个二叉搜索树,并且正在尝试实现一个递归函数来确定一个节点是否存在于二叉树中。
这是节点 class:
public class BSTNode
{
public String data; // use this for data and key
public BSTNode parent, leftchild, rightchild;
public BSTNode(String key)
{
this.data = key;
}
public Boolean Exists(String search)
{
if(data.equals(search))
return true;
else
{
if (search.compareToIgnoreCase(data) < 0 && leftchild != null)
{
leftchild.Exists(search);
}
else if (search.compareToIgnoreCase(data) > 0 && rightchild != null)
{
rightchild.Exists(search);
}
}
return false;
}
public void Insert(String key)
{
if(key.compareToIgnoreCase(data) < 0)
{
if(leftchild == null)
leftchild = new BSTNode(key);
else
leftchild.Insert(key);
}
else
{
if(rightchild == null)
rightchild = new BSTNode(key);
else
rightchild.Insert(key);
}
}
}
有问题的函数是 Exists 函数。这是在 BST 的根节点上调用的,如下所示:root.Exists("Value");
Exists 函数的基本情况在最终遇到节点时正确执行,但是 return false;
语句在 return 堆栈展开时执行。我似乎无法更改函数以删除 return false;
语句。
您忘记使用递归调用返回的值:
public Boolean Exists(String search)
{
if(data.equals(search))
return true;
else
{
if (search.compareToIgnoreCase(data) < 0 && leftchild != null)
{
return leftchild.Exists(search);
}
else if (search.compareToIgnoreCase(data) > 0 && rightchild != null)
{
return rightchild.Exists(search);
}
}
return false;
}
我目前正在编写一个二叉搜索树,并且正在尝试实现一个递归函数来确定一个节点是否存在于二叉树中。
这是节点 class:
public class BSTNode
{
public String data; // use this for data and key
public BSTNode parent, leftchild, rightchild;
public BSTNode(String key)
{
this.data = key;
}
public Boolean Exists(String search)
{
if(data.equals(search))
return true;
else
{
if (search.compareToIgnoreCase(data) < 0 && leftchild != null)
{
leftchild.Exists(search);
}
else if (search.compareToIgnoreCase(data) > 0 && rightchild != null)
{
rightchild.Exists(search);
}
}
return false;
}
public void Insert(String key)
{
if(key.compareToIgnoreCase(data) < 0)
{
if(leftchild == null)
leftchild = new BSTNode(key);
else
leftchild.Insert(key);
}
else
{
if(rightchild == null)
rightchild = new BSTNode(key);
else
rightchild.Insert(key);
}
}
}
有问题的函数是 Exists 函数。这是在 BST 的根节点上调用的,如下所示:root.Exists("Value");
Exists 函数的基本情况在最终遇到节点时正确执行,但是 return false;
语句在 return 堆栈展开时执行。我似乎无法更改函数以删除 return false;
语句。
您忘记使用递归调用返回的值:
public Boolean Exists(String search)
{
if(data.equals(search))
return true;
else
{
if (search.compareToIgnoreCase(data) < 0 && leftchild != null)
{
return leftchild.Exists(search);
}
else if (search.compareToIgnoreCase(data) > 0 && rightchild != null)
{
return rightchild.Exists(search);
}
}
return false;
}