BST 中的迭代与递归解决方案

发布于 2024-12-19 10:59:34 字数 699 浏览 0 评论 0原文

public double FindMin()
{
    Node current = root;
    while (!(current.left == null))
        current = current.left;
    return current.Data;
}

public double FindMax()
{
    Node current = root;
    while (!(current.right == null))
        current = current.right;
    return current.Data;
}

这是我的二叉搜索树函数的迭代解决方案,用于在 C# 中查找树中的最小值和最大值。我想将其更改为递归,但该代码似乎不正确,

public double RecurfindMax(Node current)
{
    //current = root;
    if (current.left == null)
    {
        return -1;
    }
    else
    //if (current.left != null)
    {
        return RecurfindMax(current = current.left);
        //return current;
    }

那么您能告诉我这段代码有什么问题吗?

public double FindMin()
{
    Node current = root;
    while (!(current.left == null))
        current = current.left;
    return current.Data;
}

public double FindMax()
{
    Node current = root;
    while (!(current.right == null))
        current = current.right;
    return current.Data;
}

This is an iterative solution of my Binary search tree's functions to find out minimum and maximum value in a tree in C#. I want to change it to recursive but that code doesn't seem right here

public double RecurfindMax(Node current)
{
    //current = root;
    if (current.left == null)
    {
        return -1;
    }
    else
    //if (current.left != null)
    {
        return RecurfindMax(current = current.left);
        //return current;
    }

So can you tell me what's wrong with this code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

真心难拥有 2024-12-26 10:59:34

您可能需要检查How to find height of BST iteratively?来解决类似的问题;那里的解决方案应该具有指导意义。

另外,对于您的递归解决方案,它应该发出一个危险信号,表明它永远不会考虑正确的孩子。

You might want to check How to find height of BST iteratively? for a similar problem; the solutions there should be instructive.

Also, for your recursive solution, it should raise a red flag that it NEVER considers the right child.

橘味果▽酱 2024-12-26 10:59:34
    private Node FindMinRecHelper(Node current)
    {
        if (current.LeftNode == null)
        {
            return current;
        }
        else
        {
            return FindMinRecHelper(current.LeftNode);
        }
    }

    public void FindMinRec()
    {
        Node current = FindMinRecHelper(root);
        Console.WriteLine(current.Data);
    }

这里是 RECURSIVE FIND MIN 的真正实现。

    private Node FindMinRecHelper(Node current)
    {
        if (current.LeftNode == null)
        {
            return current;
        }
        else
        {
            return FindMinRecHelper(current.LeftNode);
        }
    }

    public void FindMinRec()
    {
        Node current = FindMinRecHelper(root);
        Console.WriteLine(current.Data);
    }

here the true implementation of RECURSIVE FIND MIN.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文