2017-03-08 144 views
1

代碼:查找節點值搜索樹C#

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

namespace ConsoleApplication1 
{ 
    public class Node 
    { 
     public int Value { get; set; } 

     public Node Left { get; set; } 

     public Node Right { get; set; } 

     public Node(int value, Node left, Node right) 
     { 
      Value = value; 
      Left = left; 
      Right = right; 
     } 
    } 

    public class BinarySearchTree 
    { 
     public static bool Contains(Node root, int value) 
     { 
      bool status = false; 
      if (root == null) 
      { 
       status = false; 
      } 
      else if (root.Value == value) 
      { 
       status = true; 
       return true; 
      } 
      else if (root.Value < value) 
      { 
       Contains(root.Right, value); 
      } 
      else 
      { 
       Contains(root.Left, value); 
      } 
      return status; 

     } 

     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(Contains(n2, 3)); 
      Console.ReadLine(); 
     } 
    } 
} 

問: 我曾嘗試調試這個代碼呢!但它始終顯示虛假的答案。讓我知道我要去哪裏錯了。當我調試代碼時,狀態更改爲true,但仍然執行其他內容並最終更改爲false。讓我知道我要去的地方

回答

2

看樣子你是從Contains調用缺少status分配:

status = Contains(root.Right, value); 

and

status = Contains(root.Left, value); 
+0

謝謝!解決了! – RAS

2

在你的遞歸調用中,你計算子節點的Contains,但你什麼也不做。你應該結果值賦給status

public static bool Contains(Node root, int value) 
{ 
    bool status = false; 
    if (root == null) 
    { 
     status = false; 
    } 
    else if (root.Value == value) 
    { 
     status = true; 
     return true; 
    } 
    else if (root.Value < value) 
    { 
     status = Contains(root.Right, value); 
    } 
    else 
    { 
     status = Contains(root.Left, value); 
    } 
    return status; 
} 

更好的是要避免這種status變量,直接使用return聲明:

public static bool Contains(Node root, int value) 
{ 
    if (root == null) 
    { 
     return false; 
    } 
    else if (root.Value == value) 
    { 
     return true; 
    } 
    else if (root.Value < value) 
    { 
     return Contains(root.Right, value); 
    } 
    else 
    { 
     return Contains(root.Left, value); 
    } 
} 
+0

完美!這解決了我的問題。非常感謝!我想當我打電話時,它會檢查前面的if語句中的值,如果找到匹配項,它將被分配給狀態! – RAS

+0

@RAS歡迎您 –