【问题标题】:Recursive Search Binary Tree C#递归搜索二叉树 C#
【发布时间】:2015-11-13 20:35:27
【问题描述】:

我正在尝试找出这个程序是否可以检查二叉树是否是 BST,

以下是代码:

public static bool isValidBST(Node root)
    {
        return isValid(root, root.Left.Value,
             root.Right.Value);
    }

    private static bool isValid(Node node, int MIN, int MAX)
    {
        // tree with no childres is BST
        if (node == null)
            return true;

        if (node.Value <= MIN || node.Value >= MAX)
            return false;

        return isValid(node.Left, MIN, node.Value) && isValid(node.Right, node.Value, MAX);    
    }

我认为我的代码中缺少一些东西,例如,我认为此代码不适用于具有一个根和两个节点的树。你们能帮我修复我的实现吗?

我也在stackoverflow找到了这个解决方案

private static bool isValid(Node node, int MIN, int MAX)
    {
        // tree with no childres is BST
        if (node == null)
            return true;

        if (node.Value > MIN && node.Value < MAX
            && isValid(node.Left, MIN, Math.Min(node.Value, MAX))
            && isValid(node.Right, Math.Max(node.Value, MIN), MAX))
            return true;
        else
            return false;
    }

但这对我不起作用!

这就是我尝试代码的方式:

 public static void Main(string[] args)
    {
        Node n1 = new Node(1, null, null);
        Node n3 = new Node(3, null, null);
        Node n2 = new Node(2, n1, n3);

        Console.WriteLine(isValidBST(n2));
        Console.ReadLine();
    }

结果是假的,而应该是真。

【问题讨论】:

  • 那么当您在 1 节点树上运行该代码时会发生什么?你说你认为它行不通;但是您是否真的尝试过并看到会发生什么?
  • @Servy 是的,我做了兄弟,弄错了
  • 当您调试程序并查看每个节点的验证方式时,哪些节点验证正确,哪些验证错误?
  • 更好的问题是当你use the Debugger 并单步执行代码时会发生什么,你能找出你的逻辑缺陷发生在哪里吗..?
  • 如果您使用调试器step,您将看到返回false 的条件,然后在分析后您应该能够找到错误所在。

标签: c# algorithm binary-tree binary-search-tree


【解决方案1】:

您的解决方案的起点有错误:

public static bool isValidBST(Node root)
{
    return isValid(root, root.Left.Value,
        root.Right.Value);
}

不要在递归函数中传递root.Left.Valueroot.Right.Value,而是发送int.MaxValueint.MinValue。这样做至少有两个充分的理由:

  • 如果根节点没有左子或右子,你的做法会导致 NullReferenceException
  • 通过传递int.MaxValueint.MinValue,您只要求左右子节点小于/大于其父节点,没有其他边界。例如,您不应该关心第一个左孩子是否大于某个特定值,它只需要小于根值即可!通过发送int.MinValue,您可以确保它始终大于该值,因此您只需检查上限。

【讨论】:

  • 还有比这更好的解决方案吗?
  • 我不认为 Math.Min\Max 是必要的。如果您已经检查 if (node.Value = MAX) 返回 false;那么你保证 node.Value 小于 Max 并且大于 Min.
  • @Klark 你是对的,我犯了一个愚蠢的错误。感谢您指出,我已经编辑了答案。
  • @Kob_24 就时间复杂度而言 - 不,因为您需要检查树中的所有节点以检查它是否是 BST,因此 O(N)。
猜你喜欢
  • 2013-04-14
  • 2014-01-02
  • 1970-01-01
  • 2021-07-03
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 2015-06-16
相关资源
最近更新 更多