【发布时间】:2016-02-17 16:18:32
【问题描述】:
我目前正在编写一个二叉搜索树,目前正在尝试实现一个递归函数来确定一个节点是否存在于二叉树中。
这是节点类:
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 false; 语句。
【问题讨论】:
标签: java recursion binary-search-tree