簡體   English   中英

遞歸搜索二叉樹C#

[英]Recursive Search Binary Tree C#

我試圖找出該程序是否可以檢查二叉樹是否為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();
    }

結果為False,而應為True。

解決方案的起點出現錯誤:

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 ,並且沒有其他邊界。 例如,您不必在意第一個左孩子是否大於某個特定值,而不必小於根值! 通過發送int.MinValue您可以確保它始終大於該值,因此您只是在檢查上限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM