目录:
- 代码:
- 分析:
- 汇编:
代码:
BTree.h
BTree.c
二叉树(多路平衡搜索树)
SeqList.h
SeqList.c
顺序表
main.c
#include <stdio.h>
#include <stdlib.h>
#include "BTree.h"
#include "SeqList.h"struct Node//树节点
{BTreeNode header;char v;
};void printf_data(BTreeNode* node)
{if( node != NULL ){printf("%c", ((struct Node*)node)->v);}
}
//定义将树的所有节点设置成可以向左一直访问节点
//只是从左开始向右,依次将未尾节点的在子节点指向另一个节点,实现可以向左一直访问
//并不是将整个树结构改变
void thread_via_left(BTreeNode* root, BTreeNode** pp)
{//节点不为空与节点指针不为空//注意:这里其实第一次后只会判断第一个条件,因为pp一直有指向节点指针变量,只是指向的//节点指针变量指向的节点会为空。这是在里面判断if( (root != NULL) && (pp != NULL) ){if( *pp != NULL )//当前这个节点指针不为空{(*pp)->left = root;//将这个指针指向的节点指针的节点的左子节点设为当前传来的节点*pp = NULL;//当前这个指针指向的节点指针的节点的左子节点已经有指向,将这个指针设空,不再指向这个节点}if( root->left == NULL )//如果传来的节点的左子节点为空{*pp = root;//将指向节点指针指向的节点等于传来的节点,表示下次传来的节点将作为这个节点的左子节点}thread_via_left(root->left, pp);thread_via_left(root->right, pp);}
}void thread_via_list(BTreeNode* root, SeqList* list)//将树子节点全部插入顺序表
{if( (root != NULL) && (list != NULL) ){SeqList_Insert(list, (SeqListNode*)root, SeqList_Length(list));thread_via_list(root->left, list);thread_via_list(root->right, list);}
}int main(int argc, char *argv[])
{BTree* tree = BTree_Create();//创建一个树BTreeNode* current = NULL;BTreeNode* p = NULL;SeqList* list = NULL;//顺序表指针int i = 0;struct Node n1 = {{NULL, NULL}, 'A'};struct Node n2 = {{NULL, NULL}, 'B'};struct Node n3 = {{NULL, NULL}, 'C'};struct Node n4 = {{NULL, NULL}, 'D'};struct Node n5 = {{NULL, NULL}, 'E'};struct Node n6 = {{NULL, NULL}, 'F'};BTree_Insert(tree, (BTreeNode*)&n1, 0, 0, 0);BTree_Insert(tree, (BTreeNode*)&n2, 0x00, 1, 0);BTree_Insert(tree, (BTreeNode*)&n3, 0x01, 1, 0);BTree_Insert(tree, (BTreeNode*)&n4, 0x00, 2, 0);BTree_Insert(tree, (BTreeNode*)&n5, 0x02, 2, 0);BTree_Insert(tree, (BTreeNode*)&n6, 0x02, 3, 0);printf("Full Tree: \n");BTree_Display(tree, printf_data, 4, '-');printf("Thread via List:\n");list = SeqList_Create(BTree_Count(tree));//创建顺序表容量是树的节点数量thread_via_list(BTree_Root(tree), list);//调用函数将树节点插入到表中for(i=0; i<SeqList_Length(list); i++){printf("%c, ", ((struct Node*)SeqList_Get(list, i))->v);//输出:ABDEFC}printf("\n");printf("Thread via Left:\n");current = BTree_Root(tree);//取得根节点thread_via_left(current, &p);while( current != NULL ){printf("%c, ", ((struct Node*)current)->v);current = current->left;//输出:ABDEFC}printf("\n");BTree_Destroy(tree);getchar();return 0;
}
分析:
汇编: