用c语言1.编写函数,输入字符序列,建立二叉树的二叉链表 2.编写函数,实现二叉树的中序递归遍历算法。 3.编写函数,实现二叉树的中序非递归遍历算法 4.编写函数,借助队列实现二叉树的层次遍历算法 5.编写函数,求二叉树的高度 6.编写函数,求二叉树的结点个数 7.编写函数,求二叉树的叶子个数 8.编写函数,交换二叉树每个结点的左子树和右子树
时间: 2023-06-03 12:08:03 浏览: 66
这些问题属于编程类问题,我可以回答。
1. 下面是用C语言编写输入字符序列,建立二叉树的二叉链表的函数:
```c
typedef struct BiNode {
char data;
struct BiNode *left;
struct BiNode *right;
} BiNode, *BiTree;
void createBiTree(BiTree *root) {
char ch;
scanf("%c", &ch);
if (ch == '#') {
*root = NULL;
} else {
*root = (BiNode *) malloc(sizeof(BiNode));
(*root)->data = ch;
createBiTree(&((*root)->left));
createBiTree(&((*root)->right));
}
}
```
2. 下面是用C语言编写实现二叉树的中序递归遍历算法的函数:
```c
void inOrder(BiTree tree) {
if (tree != NULL) {
inOrder(tree->left);
printf("%c ", tree->data);
inOrder(tree->right);
}
}
```
3. 下面是用C语言编写实现二叉树的中序非递归遍历算法的函数:
```c
void inOrderNonRecursion(BiTree tree) {
BiNode *stack[10000];
int top = -1;
BiNode *p = tree;
while (p != NULL || top != -1) {
while (p != NULL) {
stack[++top] = p;
p = p->left;
}
if (top != -1) {
p = stack[top--];
printf("%c ", p->data);
p = p->right;
}
}
}
```
4. 下面是用C语言编写借助队列实现二叉树的层次遍历算法的函数:
```c
void levelOrder(BiTree tree) {
BiNode *queue[10000];
int front = 0, rear = 0;
if (tree != NULL) {
queue[++rear] = tree;
while (front != rear) {
front++;
BiNode *p = queue[front];
printf("%c ", p->data);
if (p->left != NULL) {
queue[++rear] = p->left;
}
if (p->right != NULL) {
queue[++rear] = p->right;
}
}
}
}
```
5. 下面是用C语言编写求二叉树的高度的函数:
```c
int getHeight(BiTree tree) {
if (tree == NULL) {
return 0;
} else {
int leftHeight = getHeight(tree->left);
int rightHeight = getHeight(tree->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
}
```
6. 下面是用C语言编写求二叉树的结点个数的函数:
```c
int getNodeCount(BiTree tree) {
if (tree == NULL) {
return 0;
} else {
return getNodeCount(tree->left) + getNodeCount(tree->right) + 1;
}
}
```
7. 下面是用C语言编写求二叉树的叶子个数的函数:
```c
int getLeafCount(BiTree tree) {
if (tree == NULL) {
return 0;
}
if (tree->left == NULL && tree->right == NULL) {
return 1;
} else {
return getLeafCount(tree->left) + getLeafCount(tree->right);
}
}
```
8. 下面是用C语言编写交换二叉树每个结点的左子树和右子树的函数:
```c
void swapBiTree(BiTree tree) {
if (tree != NULL) {
BiNode *temp = tree->left;
tree->left = tree->right;
tree->right = temp;
swapBiTree(tree->left);
swapBiTree(tree->right);
}
}
```