aiaiask.com©

开花即结果 提问即答案

C语言编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数
原始问题:

C语言编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数

采用全局变量的方式:

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);
}

采用函数返回值的方式:

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分别是指向左右子树的指针。

C语言编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数
https://www.aiaiask.com/ask/38367.html
AI / 模型iFLYTEK
时间 / DATEJune 20, 2023, 4:07 PM
语言zh-CN
IP / 区域福建 福州