我正在c#中創建一個二叉搜索樹類。我通過派生二叉樹類來創建類,因爲二叉搜索樹是一種二叉樹。因此,我將在二叉樹類中使用大多數常用方法,並在二叉搜索樹內共享它們。 BinaryTree類有兩種方法「AddToLeft」和「AddToRight」方法,這兩種方法必須能夠在這個類之外訪問,即在Main方法中向二叉樹添加節點。所以我讓他們公開。並且這兩種方法也應該在二元搜索樹類(reusing)內部可訪問以基於條件向二元搜索樹中添加節點。設計從二叉樹類繼承的二叉搜索樹類
但是現在,由於Insert方法是binarysearchtree將節點插入BST的候選者,但AddToLeft和AddToRight不是。所以這兩種方法不應該暴露給BST對象上的二進制搜索樹的客戶端(外部世界)。如何設計這個班級?
我想:
- 使得在二叉樹類密封這兩種方法,它並沒有幫助。
- 宣佈他們在基地公開和受保護的派生。這也沒有幫助,因爲公共不能在派生類中被繼承。
請幫助設計類。
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
}
}
是的,您的意見是有道理的,當BinarySearchTree是一種BinaryTree,它必須遵守BinaryTree給出的合同。所以我會比繼承更喜歡構圖。 –