簡體   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