java 继承树设计_设计继承二叉树类的二叉搜索树类

本文讨论了如何在Java中设计二叉搜索树类,通过从二叉树类继承实现。作者面临的问题是,二叉树类的`AddToLeft`和`AddToRight`方法需要在主方法中使用,但不应直接暴露在二叉搜索树的客户端。解决方案是在基类中声明这些方法为受保护的,以便在派生类中使用,同时防止外部直接访问。
摘要由CSDN通过智能技术生成

我在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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值