C# - 二进制搜索树包含/是现有方法

时间:2016-11-30 21:39:53

标签: c# binary-search-tree

我真的很难让这种方法起作用,我想知道你是否可以帮助我。我一直在使用ref关键字,所以我会继续使用它。我一直在网上搜索,这是一些帮助,但我已经尝试了我能想到的一切。我的计数和高度方法都有效,但是,我真的很难让这个Contain方法起作用。网上的很多例子都显示了包含公共和私有方法(我理解为什么),但我确信它可以在一个方法中完成?当然,对吧?此外,请忽略RemoveItem方法,除非您希望给我一个先发制人,这是您自行决定的。我知道这很棘手,因为我在本周早些时候看过它。

节点类 -

Structure gameObjects
 BirdPic as Image
 BirdPicName as string
 Position as Point
End Structure

DIM GamePictures(0) AS gameObjects

SUB Main()

    ' Create a new object
    DIM newObj as New gameObjects
    With newObj
         .BirdPic = Image.FromFile("pics/bluejay.jpg")
         .BirdPicName = "BlueJay"
         .Position = new point(10, 20)
    End With
    AddObject(newObj)




    for index = 0 to gamepictures.count - 1
        If tbxAnimal_Group.Text = "Birds" AND GamePictures(index).BirdPicName = "BlueJay" THEN
            ' Do Something
        End If
    next
END SUB 


Public Sub AddObject(obj as GameObjects)
       DIM thisObjIndex as integer = GamePictures.Count 
       ReDim preserve GamePictures(thisObjIndex + 1)

       GamePictures(thisObjIndex) = obj
End Sub 

BinTree类 -

    class Node<T> where T : IComparable
{
    private T data;
    public Node<T> Left, Right;

    public Node(T item)
    {
        data = item;
        Left = null;
        Right = null;
    }
    public T Data
    {
        set { data = value; }
        get { return data; }
    }

}

BSTree类 -

 class BinTree<T> where T : IComparable
{
    protected Node<T> root;

    public BinTree()  //creates an empty tree
    {
        root = null;
    }
    public BinTree(Node<T> node)  //creates a tree with node as the root
    {
        root = node;
    }
   //I've deleted my preOrder, inOrder and postOrder methods just to save you some time

}

提前谢谢你。

2 个答案:

答案 0 :(得分:2)

要检查节点是否在树中,您有几个选项:

  1. 您想要的节点位于左侧子树
  2. 您想要的节点位于正确的子树
  3. 您想要的节点就在您现在所在的位置
  4. 因此,您的Contains方法应该更像这样:

    public Boolean Contains(T item, ref Node<T> tree)
    {
           if (tree == null)
           {
                return false;
           }
    
           if (tree.data == item)
           {
               return true;
           }  
    
    
           if (item.CompareTo(tree.Data) < 0)
           {
                return Contains(item, ref tree.Left);
           }
           if (item.CompareTo(tree.Data) > 0)
           {
                return Contains(item, ref tree.Right);
           }
      }
    

答案 1 :(得分:0)

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