【问题标题】:Iterative vs recursive solution in BSTBST 中的迭代与递归解决方案
【发布时间】:2011-12-05 21:31:20
【问题描述】:
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;
    }

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

【问题讨论】:

    标签: c# data-structures


    【解决方案1】:

    您可能想检查How to find height of BST iteratively? 是否有类似问题;那里的解决方案应该是有启发性的。

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

    【讨论】:

    • 谢谢我知道递归的问题是因为标志..谢谢
    【解决方案2】:
        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 的真正实现。

    【讨论】:

      猜你喜欢
      • 2013-07-22
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2020-10-30
      • 2016-12-15
      相关资源
      最近更新 更多