【问题标题】:Binary Search Tree in C# Search MethodC#搜索方法中的二叉搜索树
【发布时间】:2013-01-13 02:54:25
【问题描述】:
public bool Searchtree(Node root, int target)
    {
        if (root == null) return false;

        else if (target < root.data)
            Searchtree(root.left, target);

        else if (target > root.data)
            Searchtree(root.right, target);

        if (target == root.data)
        {
            //Console.WriteLine("Found: "+root.data);
            return true;
        }

        else
            return false;
    }

这是一种在二叉搜索树中搜索整数的方法

方法调用将是:binary.Searchtree(binary.root, 2);

但它总是返回 False,即使它打印了 Writeline。

【问题讨论】:

  • 您需要将递归调用的结果返回给Searchtree。
  • 换一种说法:在你上面的当前代码中,那些递归调用Searchtree的目的是什么?
  • 我想我明白了,现在递归调用什么都不做。 return Searchtree(root.right, target); 会做我认为的伎俩吗?
  • 感谢 Oli Charlesworth 和 LeffeBrune

标签: c# data-structures binary-search-tree


【解决方案1】:

返回对 Searchtree 的调用结果:

public bool Searchtree(Node root, int target)
{
    if (root == null)
        return false;
    else if (target < root.data)
        return Searchtree(root.left, target);
    else if (target > root.data)
        return Searchtree(root.right, target);

    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多