C语言编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数
采用全局变量的方式:
```c
int count = 0; // 全局变量
void countDegree2(TreeNode* root) {
if (root == NULL) {
return;
}
if (root->left != NULL && root->right != NULL) {
count++;
}
countDegree2(root->left);
countDegree2(root->right);
}
```
采用函数返回值的方式:
```c
int countDegree2(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftCount = countDegree2(root->left);
int rightCount = countDegree2(root->right);
if (root->left != NULL && root->right != NULL) {
return leftCount + rightCount + 1;
} else {
return leftCount + rightCount;
}
}
```
其中,TreeNode是二叉树的结点类型,left和right分别是指向左右子树的指针。
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。