【问题标题】:Recursive function return incorrectly returns false递归函数返回错误返回false
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2021-06-18
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2016-02-05
      相关资源
      最近更新 更多