目錄:
- 代碼:
- 分析:
- 匯編:
代碼:
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;
}
分析:
匯編: