1、指路法定位结点
从根结点开始,指出访问每个结点所走的路径。
- 指路法通过根结点与目标结点的相对位置进行定位
- 指路法可以避开二叉树递归的性质“线性”定位
2、指路法的实现
在C语言中可通过bit位来指路,如果bit位为0,则“左转”,如果bit位为1,则“右转”;
定义如下:
#define BT_LEFT 0
#define BT_RIGHT 1
typedef unsigned long long BTPos; //指定寻找"路径"
3、二叉树存储结构定义
- 用结构体来定义二叉树中的指针域
- 二叉树的头结点也可以用结构体实现
结点指针域的定义:
typedef struct _struct_btreenode BTreeNode;
struct _struct_btreenode
{
BTreeNode *left;
BTreeNode *right;
};
头结点定义:
typedef struct _struct_tbtree
{
int count;
BTreeNode *root;
}TBTree;
数据结点定义:
typedef struct _struct_node
{
BTreeNode header;
char v;
}Node;
4、二叉树的定位操作
关键技巧:
- 利用二进制中的 0 和 1 分别表示left和right
- 位运算是实现指路法的基础
while((count > 0) && (current != NULL))
{
bit = pos & 1;
pos = pos >> 1;
parent = current;
if(bit == BT_LEFT)
{
current = current->left;
}
else if(bit == BT_RIGHT)
{
current = current->right;
}
count--;
}
6、元素的插入操作
/*
将结点node插入到BTree中的pos位置处
插入成功,返回1,失败,返回0
*/
int BTree_Insert(BTree* tree, BTreeNode* node, BTPos pos,int count,int flag)
{
TBTree *btree = (TBTree*)tree;
int iret = (btree != NULL) && (node != NULL) && ((flag == BT_LEFT) || (flag == BT_RIGHT));
if(iret)
{
BTreeNode *parent = NULL;
BTreeNode *current = btree->root;
int bit = 0;
while((count > 0) && (current != NULL))
{
bit = pos & 1;
pos = pos >> 1;
parent = current;
if(bit == BT_LEFT)
{
current = current->left;
}
else if(bit == BT_RIGHT)
{
current = current->right;
}
count--;
}
if(flag == BT_LEFT)
{
node->left = current;
}
else if(flag == BT_RIGHT)
{
node->right = current;
}
if(parent != NULL)
{
if(bit == BT_LEFT)
{
parent->left = node;
}
else if(bit == BT_RIGHT)
{
parent->right = node;
}
}
else
{
btree->root = node;
}
btree->count++;
}
return iret;
}
7、元素的删除操作
static int recursive_count(BTreeNode *root)
{
int iret = 0;
if(root != NULL)
{
iret = recursive_count(root->left) + recursive_count(root->right) + 1;
}
return iret;
}
/*
将BTree中pos位置的结点删除并返回其中的数据
删除成功,返回结点中的数据指针,失败,返回NULL
*/
BTreeNode* BTree_Delete(BTree* tree, BTPos pos,int count)
{
BTreeNode *ret = NULL;
TBTree *btree = (TBTree*)tree;
if(btree != NULL)
{
BTreeNode *parent = NULL;
BTreeNode *current = btree->root;
int bit = 0;
while((count > 0)&&(current != NULL))
{
bit = pos & 1;
pos = pos >> 1;
parent = current;
if(bit == BT_LEFT)
{
current = current->left;
}
else if(bit == BT_RIGHT)
{
current = current->right;
}
count--;
}
if(parent != NULL)
{
if(bit == BT_LEFT)
{
parent->left = NULL;
}
else if(bit == BT_RIGHT)
{
parent->right = NULL;
}
}
else
{
btree->root = NULL;
}
ret = current;
btree->count -= recursive_count(current);
}
return ret;
}
8、小结
- 二叉树在结构上不依赖组织链表
- 通过指路法可以方便的定位二叉树中的结点
- 基于指路法的二叉树在插入,删除和获取操作的实现细节上与单链表相似
9、完整源码下载
文件名:btree-1.0.tar.gz
链接: http://pan.baidu.com/s/1kTKj7pX 密码: mvv7
编译步骤:
编译步骤:
0.1 解压缩:tar -zxvf btree-1.0.tar.gz
0.2 进入目录:./configure
0.3 生成Seqlist:make
0.4 运行程序:./BTree