C#中的二叉树

本文关键字:二叉树 | 更新日期: 2023-09-27 17:58:11

如何在C#中创建一个简单、直接、不使用任何预定义类的二进制树?我说的是一些简单的事情,就像你在C++中所做的那样

与NGenerics完全不同表示树的对象

我的意思是从一些简单的事情开始,比如:

struct
{
  Node * left
  Node * right
  int value;
}

后续问题:

好的,如果我有这个:

public class binarytreeNode
{
    public binarytreeNode Left;
    public binarytreeNode Right;
    public int data;
}

我是否必须将作用于节点的方法放在这个类中?这不是让它不再是一个节点吗?

如果我创建了一个在Program类中添加节点的方法:

class Program
{       
     public binarytreeNode AddNode(int value)
    {
        binarytreeNode newnode = new binarytreeNode();
        newnode.Left = null;
        newnode.Right = null;
        newnode.data = value;
        return newnode;
    }
     static void Main(string[] args)
    {
        binarytreeNode head = AddNode(4);
    }
}

编译器说,我对AddNode的调用需要一个对象引用。为什么?

C#中的二叉树

class Node<T>
{
    public Node<T> Left, Right;
    public T Value;
}
class Node
{
  public Node left, right;
  public int value;
}
namespace ConsoleApplication1
{
    public class binarytreeNode
    {
        public binarytreeNode Left;
        public binarytreeNode Right;
        public int data;
    }
    public class binarytree
    {
        public binarytreeNode AddNode(int value)
            {
                binarytreeNode newnode = new binarytreeNode();
                newnode.Left = null;
                newnode.Right = null;
                newnode.data = value;
                return newnode;
            }
    }
    class Program
    {       
         static void Main(string[] args)
        {
            binarytree mybtree = new binarytree();
            binarytreeNode head = mybtree.AddNode(4);
        }
    }
}