C语言编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数,并说明如何调用编写的函数
采用全局变量方式:
```c
#include <stdio.h>
int count = 0; // 全局变量
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void countNodes(struct TreeNode* root) {
if (root == NULL) {
return;
}
if (root->left != NULL && root->right != NULL) {
count++;
}
countNodes(root->left);
countNodes(root->right);
}
int main() {
// 构造二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
countNodes(root);
printf("度为2的结点个数为:%d
", count);
return 0;
}
```
采用函数返回值方式:
```c
#include <stdio.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int countNodes(struct TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftCount = countNodes(root->left);
int rightCount = countNodes(root->right);
if (root->left != NULL && root->right != NULL) {
return leftCount + rightCount + 1;
} else {
return leftCount + rightCount;
}
}
int main() {
// 构造二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
int count = countNodes(root);
printf("度为2的结点个数为:%d
", count);
return 0;
}
```
调用方式:
```c
int main() {
// 构造二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
// ...
// 调用函数
int count = countNodes(root);
// ...
}
```
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。