本文為「C語言范例學習」系列第三部分,完整實現二叉樹創建與三種遍歷、哈夫曼編碼構建、無向圖的深度/廣度優先搜索(DFS/BFS),代碼均可直接編譯運行。
typedef struct Node {
struct Node *lchild;
char data;
struct Node *rchild;
} BiNode, *BiTree;
BiTree CreateTree() {
char ch; scanf("%c", &ch);
if (ch == '#') return NULL;
BiTree t = malloc(sizeof(BiNode));
t->data = ch;
t->lchild = CreateTree();
t->rchild = CreateTree();
return t;
}
void PreOrder(BiTree t) { // 根-左-右
if (t) { putchar(t->data); PreOrder(t->lchild); PreOrder(t->rchild); }
}
void InOrder(BiTree t) { // 左-根-右
if (t) { InOrder(t->lchild); putchar(t->data); InOrder(t->rchild); }
}
void PostOrder(BiTree t) { // 左-右-根
if (t) { PostOrder(t->lchild); PostOrder(t->rchild); putchar(t->data); }
}
int Depth(BiTree t) {
if (!t) return 0;
return 1 + (Depth(t->lchild) > Depth(t->rchild) ? Depth(t->lchild) : Depth(t->rchild));
}
int NodeCount(BiTree t) { return t ? NodeCount(t->lchild) + NodeCount(t->rchild) + 1 : 0; }
int LeafCount(BiTree t) {
if (!t) return 0;
if (!t->lchild && !t->rchild) return 1;
return LeafCount(t->lchild) + LeafCount(t->rchild);
}
輸入:ABD##E##CF##G##(先序,# 為空)
contents of binary tree: DBEAFCG (中序輸出) depth of binary tree: 3 the number of the nodes: 7 the number of the leaf nodes: 4 preorder traversal: ABD#E#CF#G# inorder traversal: DBEAFCG postorder traversal: DEBFGCA
typedef struct { char data; int weight; int parent, left, right; int flag; } HuffNode;
typedef struct { char code[50]; int start; } HuffCode;
huffman is: a: 010 b: 011 c: 000 d: 001 e: 10 f: 11
高頻字符(f, e)編碼短,低頻(c, d)編碼長,符合最優前綴碼原理。
struct Node { int vertex, flag; struct Node *next; };
struct Node V[10]; // 頂點表頭
void DFS(int v) {
V[v].flag = 1; printf("vertex[%d] ", v);
for (struct Node *p = V[v].next; p; p = p->next)
if (!V[p->vertex].flag) DFS(p->vertex);
}
void BFS(int v) {
int q[100], front=-1, rear=-1;
q[++rear] = v; V[v].flag = 1; printf("vertex[%d] ", v);
while (front != rear) {
int cur = q[++front];
for (struct Node *p = V[cur].next; p; p = p->next)
if (!V[p->vertex].flag) {
q[++rear] = p->vertex;
V[p->vertex].flag = 1;
printf("vertex[%d] ", p->vertex);
}
}
}

DFS: vertex[1] vertex[2] vertex[4] vertex[5] vertex[3] vertex[6] BFS: vertex[1] vertex[2] vertex[3] vertex[4] vertex[5] vertex[6]
數據結構在計算機考研專業課中佔比 80% 以上,更是編程思想的具體化。下一章進入算法專題,將側重「思想引導算法,算法體現思想」。