c语言写一个求二叉树结点个数的程序
时间: 2024-05-10 14:19:49 浏览: 18
好的,下面是求二叉树结点个数的C语言程序:
```c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *left;
struct Node *right;
}Node;
Node* createTree(){ //创建一棵二叉树
Node* root = (Node*)malloc(sizeof(Node));
root->data = 1;
Node* p1 = (Node*)malloc(sizeof(Node));
p1->data = 2;
p1->left = NULL;
p1->right = NULL;
Node* p2 = (Node*)malloc(sizeof(Node));
p2->data = 3;
p2->left = NULL;
p2->right = NULL;
Node* p3 = (Node*)malloc(sizeof(Node));
p3->data = 4;
p3->left = NULL;
p3->right = NULL;
Node* p4 = (Node*)malloc(sizeof(Node));
p4->data = 5;
p4->left = NULL;
p4->right = NULL;
root->left = p1;
root->right = p2;
p1->left = p3;
p1->right = NULL;
p2->left = p4;
p2->right = NULL;
return root;
}
int countNodes(Node* root){ //求二叉树结点个数
if(root == NULL){
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
int main(){
Node* root = createTree();
int num = countNodes(root);
printf("The total number of nodes is %d",num);
return 0;
}
```
输出结果为:The total number of nodes is 5。