gpt4 book ai didi

java - 递归函数返回错误返回false

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:06:49 24 4
gpt4 key购买 nike

我目前正在编写一个二叉搜索树,并且正在尝试实现一个递归函数来确定一个节点是否存在于二叉树中。

这是节点类:

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; 语句。

最佳答案

您忘记使用递归调用返回的值:

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

关于java - 递归函数返回错误返回false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35462140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com