双向链表好像实现通讯更稳定,突然想到能否用lpc来试试二叉树呢?
下面是源代码:
/**
* +|------------------------------------------------------|+
* 用LPC实现二叉树的算法测试
* +|------------------------------------------------------|+
*/
class BinaryTree
{
mixed Data;
class BinaryTree LTree;
class BinaryTree RTree;
}
/*生成以data为根节点的左子树为ltree,右子树为rtree的二叉树*/
class BinaryTree create_binarytree(mixed data,class BinaryTree ltree,class BinaryTree rtree)
{
class BinaryTree btree;
btree = new(class BinaryTree);
btree->Data = data;
btree->LTree = ltree;
btree->RTree = rtree;
return btree;
}
//插入一个左子树
class BinaryTree insert_Ltree(class BinaryTree btree,mixed data,class BinaryTree Parent)
{
class BinaryTree bt;
if(!Parent) return bt;
bt = new(class BinaryTree);
bt->Data = data;
if(!Parent->LTree) Parent->LTree = bt;
else {
bt->LTree = Parent->LTree;
Parent->LTree = bt;
}
return btree;
}
//查询
class BinaryTree serch(class BinaryTree btree,mixed data)
{
class BinaryTree p;
if(btree->Data == data) return btree;
if(classp(btree->LTree)) {
return serch(btree->LTree,data);
}
if(classp(btree->RTree)) {
return serch(btree->RTree,data);
}
return p;
}
mixed main()
{
class BinaryTree btree,p,Parent;
int i;
btree = new(class BinaryTree);
p = btree;
for(i=1;i<3;i++) {
message("system",sprintf("i%O/n",i),users());
message("system",sprintf("btree:%O/n",btree),users());
if(!insert_Ltree(btree,i,p)) {
return 0;
}
p = serch(btree->LTree,i);
message("system",sprintf("p:%O/n",p),users());
}
Parent = btree->LTree;
while(classp(Parent)) {
message("system",sprintf("%d/n",Parent->Data),users());
Parent = Parent->LTree;
}
}
测试下来打印在终端的结果为:
i1
btree:CLASS( 3 elements
0,
0,
0
)
p:CLASS( 3 elements
1,
0,
0
)
i2
btree:CLASS( 3 elements
0,
CLASS( 3 elements
1,
0,
0
),
0
)
p:CLASS( 3 elements
2,
0,
0
)
1
2
验证好像是对的哦。:),上面只是简单的insert左子树。