我正在 C# 中创建一个二叉搜索树类。我通过从二叉树类派生来创建该类,因为二叉搜索树是一种二叉树。所以我将在二叉树类中拥有大部分常用方法,并在二叉搜索树中共享它们。
现在:BinaryTree 类有两个方法“AddToLeft”和“AddToRight”方法,这两个方法必须能够在这个类之外访问,即在Main 方法中向二叉树添加节点。所以我把它们公开了。并且这两种方法也应该可以在二叉搜索树类(重用)中访问,以根据条件将节点添加到二叉搜索树。
但是现在由于 Insert 方法是二叉搜索树将节点插入 BST 的候选方法,但 AddToLeft 和 AddToRight 不是。所以这两种方法不应该暴露给我在 BST 对象上的二叉搜索树的客户端(外部世界)。如何设计这个类。?
我试过了:
- 将这两种方法密封在二叉树类中,它没有帮助。
- 在 base 中声明它们是 public 并在派生中声明它们。这也没有帮助,因为 public 不能在派生类中被继承为 protected。
请帮助设计课程。
public class BTNode
{
public int data;
public BTNode Left { get; set; }
public BTNode Right { get; set; }
public BTNode(int data)
{
this.data = data;
}
}
public class BinaryTree
{
public BTNode Root { get; set;}
public BinaryTree() : this(null) { }
public BinaryTree(BTNode node) { Root = node; }
// this method common for its derived class too
public void AddToLeft(BTNode current, BTNode node)
{
current.Left = node;
}
// this method common for its derived class too
public void AddToRight(BTNode current, BTNode node)
{
current.Right = node;
}
}
public class BinarySearchTree : BinaryTree
{
public BinarySearchTree(int val)
{
Root = new BTNode(val);
}
public void Insert(int val)
{
BTNode node = new BTNode(val);
if (Root.data >= val)
base.AddToLeft(Root, node); // I should be able to call this method here
else
base.AddToRight(Root, node); // I should be able to call this method here
}
}
class Program
{
static void Main(string[] args)
{
BinaryTree bt = new BinaryTree();
BTNode root = new BTNode(3);
BTNode node1 = new BTNode(4);
BTNode node2 = new BTNode(7);
bt.AddToLeft(root,node1); // i should be able to access this method here.
bt.AddToLeft(root, node2); // i should be able to access this method here.
BinarySearchTree bst = new BinarySearchTree(6);
bst.Insert(4);
bst.Insert(8);
// This is the problem.
// these two methods should not be visible on the bst object.
// insertion to bst is done only through insert() method
// but these two methods should be accessible inside the binarysearchtree class
// to add the nodes.
bst.AddToLeft(root,node1); // i should not access this method here on this object
bst.AddToRight(root, node2); // i should not access this method here on this object
}
}