我在c#中创建了一个二叉搜索树类 . 我是通过从二叉树类派生来创建类的,因为二叉搜索树是一种二叉树 . 所以我将在二叉树类中包含大多数常用方法,并在二叉搜索树中共享它们 .
现在:BinaryTree类有两个方法“AddToLeft”和“AddToRight”方法,这两个方法必须能够在这个类之外访问,即在Main方法中将节点添加到二叉树中 . 所以我把它们公之于众 . 并且这两个方法也应该可以在二进制搜索树类(重用)中访问,以根据条件将节点添加到binarysearchtree .
但是现在因为Insert方法是binarysearchtree将节点插入BST但是AddToLeft和AddToRight不是 . 所以这两个方法不应该暴露给BST对象上我的二叉搜索树的客户端(外部世界) . 如何设计这个课程 .
我试过了:
使这两个方法密封在binarytree类中,它没有帮助 .
在基础上声明它们是公共的并且在派生中受到保护 . 这也没有帮助,因为公共不能在派生类中被继承为受保护 .
请帮助设计课程 .
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
}
}