会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
A New Hope!
无愧于心,良机无限
博客园
首页
新随笔
联系
管理
订阅
数据结构学习(1):搜索二叉树
using
System;
using
System.IO;
namespace
BinaryTreeSearch
{
/**/
///
<summary>
///
Class1 的摘要说明。
///
</summary>
class
BinaryTreeSearch
{
/**/
///
<summary>
///
应用程序的主入口点。
///
</summary>
[STAThread]
static
void
Main(
string
[] args)
{
//
//
TODO: 在此处添加代码以启动应用程序
//
}
public
void
init()
{
//
构造一个空的二叉搜索树开始
BinarySearchTree T
=
new
BinarySearchTree();
//
T初始为空
}
}
class
BinarySearchTree
{
//
BinarySearchTree中有一个存储指向二叉搜索树根结点指针(或存有证明为空树
//
的null)的私有数据域
private
TreeNode rootNode;
//
BinarySearchTree的各种方法
//
Insert方法所用的辅助方法
private
TreeNode insertKey(TreeNode T,ComparisonKey K)
{
if
(T
==
null
)
{
TreeNode N
=
new
TreeNode();
//
构建一个新的TreeNode
N.key
=
K;
return
N;
}
else
{
if
(K.compareTo(T.key)
<
0
)
{
T.llink
=
insertKey(T.llink,K);
return
T;
}
else
{
T.rlink
=
insertKey(T.rlink,K);
return
T;
}
}
}
//
end insertKey
void
insert(
string
K)
{
rootNode
=
insertKey(rootNode,
new
StringKey(K));
}
//
end insert
TreeNode find(ComparisonKey K)
{
TreeNode T
=
rootNode;
int
result;
while
(T
!=
null
)
{
if
((result
=
K.compareTo(T.key))
<
0
)
{
T
=
T.llink;
}
else
if
(result
==
0
)
{
return
T;
}
else
{
T
=
T.rlink;
}
//
end if
}
return
T;
//
如果搜索失败 返回null
}
TreeNode find(String K)
{
return
find(
new
StringKey(K));
}
}
class
TreeNode
{
ComparisonKey key;
TreeNode llink;
TreeNode rlink;
}
public
interface
ComparisonKey
{
//
如果K1和K2均为ComparisonKey,那么K1.compareTo(k2)就会有三个值0,1,-1,
//
就是K1==K2,K1>K2,K1<K2顺序是compareTo方法定义的优先级别顺序
int
compareTo(ComparisonKey value);
//
将ComparisonKey转换成可以打印的字符串
string
toOurString();
}
public
class
PQItem:ComparisonKey
{
private
int
key;
//
key数据包括给出元素优先级别的整数关键字
public
PQItem(
int
value)
{
key
=
value;
}
ComparisonKey 成员
#region
ComparisonKey 成员
public
int
compareTo(ComparisonKey value)
{
int
a
=
this
.key;
int
b
=
((PQItem)value).key;
return
((a
==
b)
?
0
:((a
>
b)
?
1
:
-
1
));
}
public
string
toOurString()
{
return
this
.key.ToString();
}
#endregion
}
}
posted @
2006-12-14 18:58
大天使泰瑞尔
阅读(
569
) 评论(
0
)
收藏
举报
刷新页面
返回顶部
公告