用c语言编写先序遍历二叉树的递归算法,以及计算二叉树中度为1的结点个数的算法。
时间: 2024-06-13 15:07:40 浏览: 113
以下是C语言编写先序遍历二叉树的递归算法和计算二叉树中度为1的结点个数的算法:
1. 先序遍历二叉树的递归算法
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 先序遍历二叉树的递归算法
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val); // 访问根节点
preorderTraversal(root->left); // 遍历左子树
preorderTraversal(root->right); // 遍历右子树
}
int main() {
// 构建二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1; root->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 先序遍历二叉树
printf("先序遍历结果:");
preorderTraversal(root);
printf("\n");
return 0;
}
```
2. 计算二叉树中度为1的结点个数的算法
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 计算二叉树中度为1的结点个数的算法
int countDegreeOne(TreeNode* root) {
if (root == NULL) {
return 0;
}
int count = 0;
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL)) {
count++;
}
count += countDegreeOne(root->left);
count += countDegreeOne(root->right);
return count;
}
int main() {
// 构建二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 计算二叉树中度为1的结点个数
int count = countDegreeOne(root);
printf("度为1的结点个数:%d\n", count);
return 0;
}
```
阅读全文