用一段C语言实现(1) 输入字符序列,建立二叉链表。 (2) 中序遍历二叉树:递归算法。 (3)中序遍历二叉树:非递归算法。 (4)求二叉树的高度 。 (5)为N个权值设计哈夫曼编码。
时间: 2024-01-13 08:03:40 浏览: 96
这是基本数据结构及其算法的C++实现,涉及单链表、双链表、栈 、二叉树、并查集、哈夫曼树、平衡二叉树、二叉搜索树等.zip
好的,这是一个比较复杂的问题,需要分步骤回答。下面是详细的回答:
1. 输入字符序列,建立二叉链表。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _BiTreeNode {
char data;
struct _BiTreeNode *left;
struct _BiTreeNode *right;
} BiTreeNode, *BiTree;
void createBiTree(BiTree *root) {
char ch;
scanf("%c", &ch);
if (ch == '#') {
*root = NULL;
} else {
*root = (BiTreeNode *)malloc(sizeof(BiTreeNode));
(*root)->data = ch;
createBiTree(&(*root)->left);
createBiTree(&(*root)->right);
}
}
```
2. 中序遍历二叉树:递归算法。
```c
void inorderTraversal(BiTree root) {
if (root) {
inorderTraversal(root->left);
printf("%c ", root->data);
inorderTraversal(root->right);
}
}
```
3. 中序遍历二叉树:非递归算法。
```c
void inorderTraversalNonRecursive(BiTree root) {
BiTree stack[100];
int top = -1;
BiTree p = root;
while (p || top != -1) {
while (p) {
stack[++top] = p;
p = p->left;
}
if (top != -1) {
p = stack[top--];
printf("%c ", p->data);
p = p->right;
}
}
}
```
4. 求二叉树的高度。
```c
int getBiTreeHeight(BiTree root) {
if (root == NULL) {
return 0;
} else {
int leftHeight = getBiTreeHeight(root->left);
int rightHeight = getBiTreeHeight(root->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
}
```
5. 为N个权值设计哈夫曼编码。
```c
typedef struct _HuffmanTreeNode {
int weight;
int parent;
int leftChild;
int rightChild;
} HuffmanTreeNode, *HuffmanTree;
void createHuffmanTree(HuffmanTree *tree, int *weight, int n) {
if (n <= 1) {
return;
}
int m = 2 * n - 1;
*tree = (HuffmanTreeNode *)malloc(sizeof(HuffmanTreeNode) * (m + 1));
for (int i = 1; i <= n; i++) {
(*tree)[i].weight = weight[i - 1];
(*tree)[i].parent = 0;
(*tree)[i].leftChild = 0;
(*tree)[i].rightChild = 0;
}
for (int i = n + 1; i <= m; i++) {
int s1 = 0, s2 = 0;
for (int j = 1; j < i; j++) {
if ((*tree)[j].parent == 0) {
if (s1 == 0) {
s1 = j;
} else if (s2 == 0) {
s2 = j;
} else {
if ((*tree)[j].weight < (*tree)[s1].weight) {
s2 = s1;
s1 = j;
} else if ((*tree)[j].weight < (*tree)[s2].weight) {
s2 = j;
}
}
}
}
(*tree)[s1].parent = i;
(*tree)[s2].parent = i;
(*tree)[i].leftChild = s1;
(*tree)[i].rightChild = s2;
(*tree)[i].weight = (*tree)[s1].weight + (*tree)[s2].weight;
}
}
void getHuffmanCode(HuffmanTree tree, char **code, int n) {
*code = (char *)malloc(sizeof(char) * n);
char *temp = (char *)malloc(sizeof(char) * n);
temp[n - 1] = '\0';
for (int i = 1; i <= n; i++) {
int current = i;
int parent = tree[current].parent;
int index = n - 1;
while (parent != 0) {
if (tree[parent].leftChild == current) {
temp[--index] = '0';
} else {
temp[--index] = '1';
}
current = parent;
parent = tree[current].parent;
}
strcpy(&(*code)[i - 1], &temp[index]);
}
}
```
以上就是完整的程序代码,包括输入字符序列建立二叉链表、中序遍历二叉树(递归和非递归)、求二叉树的高度以及为N个权值设计哈夫曼编码。
阅读全文