繁体   English   中英

二进制搜索树验证

[英]Binary Search Tree Validation

感谢您阅读我的主题。 我在Test Dome上使用C#进行一些练习。 我当前正在尝试编写的练习如下: http : //www.testdome.com/Questions/Csharp/BinarySearchTree/484?testId=21&testDifficulty=Hard

我目前的结果:

  • 示例案例:正确答案
  • 简单案例:正确答案
  • 常规情况:答案错误
  • 极端情况:错误的答案
  • 性能测试:答案错误

您可以在下面阅读我编写的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Node
{
    public int Value { get; set; }                      // Value of {node} == integer (1,2,3,4,5)
    public Node Left { get; set; }                      // Reference to left node (n1, n2, n3) == Node.
    public Node Right { get; set; }                     // Reference to right node (n1, n2, n3) == Node.
    public Node(int value, Node left, Node right)       
    {
        Value = value;                                  // (int)
        Left = left;                                    // (node)
        Right = right;                                  // (node)
    }
}

public class BinarySearchTree
{
    public static bool IsValidBST(Node root)
    {
        if (root.Left == null && root.Right == null)
            return true;

        else if (root.Left == null)
        {
            // Checking root.Right.Value
            if (root.Value <= root.Right.Value)
                return true;

            else
                return false;
        }
        else if (root.Right == null)
        {
            // Checking root.Left.Value
            if (root.Value > root.Left.Value)
                return true;
            else
                return false; 
        }
        else
        {
            // Checking both Values
            if (root.Value > root.Left.Value && root.Value <= root.Right.Value)
                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);

        // Execute function and write it to the console
        Console.WriteLine(IsValidBST(n2));
        Console.ReadLine();
    }
}

我不知道要通过什么测试。 我不希望您给我书面代码,但要提供有关锻炼的更多信息。 请记住,我当前的代码远非整齐。 谢谢你们。

您没有检查所有上层节点的值。 您应该具有所有上层节点的数组/列表,因此可以对其进行检查。

而且您还应该使用递归调用。 像这样

IsValidBST(Node root, List<int> upperValues = null) 
{
 ... 
 bool childIsValid = IsValidBST (root.Left, upperValuesLeft ) && IsValidBST(root.Right, upperValuesRight )
}

您应该通过在其他节点上调用IsValidBST (如果它们不为null来检查其他节点root.Leftroot.Right ,然后检查这些结果。 现在,您只测试根节点,而不是下降到树中

答案代码:

if (root.Value == value) return true;

if (root.Left != null && value < root.Value)
    if (Contains(root.Left, value)) return true;

if (root.Right != null && value > root.Value)
    if (Contains(root.Right, value)) return true;

return false;

阅读关于同一问题的帖子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM