用c语言写份求二叉树中的(叶子/单分支/双分支)结点个数的代码
时间: 2024-03-23 09:41:22 浏览: 54
求二叉树叶子结点的个数(c++类建立)
5星 · 资源好评率100%
以下是用C语言实现求二叉树中叶子、单分支、双分支结点个数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 结点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 构造二叉树
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
// 计算叶子结点个数
int countLeafNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeafNodes(root->left) + countLeafNodes(root->right);
}
// 计算单分支结点个数
int countSingleBranchNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 0;
}
if (root->left == NULL && root->right != NULL) {
return 1 + countSingleBranchNodes(root->right);
}
if (root->left != NULL && root->right == NULL) {
return 1 + countSingleBranchNodes(root->left);
}
return countSingleBranchNodes(root->left) + countSingleBranchNodes(root->right);
}
// 计算双分支结点个数
int countDoubleBranchNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 0;
}
if (root->left != NULL && root->right != NULL) {
return 1 + countDoubleBranchNodes(root->left) + countDoubleBranchNodes(root->right);
}
return countDoubleBranchNodes(root->left) + countDoubleBranchNodes(root->right);
}
int main() {
TreeNode* root = createTree();
printf("叶子结点个数:%d\n", countLeafNodes(root));
printf("单分支结点个数:%d\n", countSingleBranchNodes(root));
printf("双分支结点个数:%d\n", countDoubleBranchNodes(root));
return 0;
}
```
这里我们通过递归的方式来实现计算各种类型结点的个数。其中,countLeafNodes函数用来计算叶子结点个数,countSingleBranchNodes函数用来计算单分支结点个数,countDoubleBranchNodes函数用来计算双分支结点个数。在计算单分支结点和双分支结点的时候,我们通过判断结点的左右子树是否为空来进行区分。
阅读全文