c++计算二叉树的结点个数
时间: 2024-01-28 17:05:39 浏览: 77
计算二叉树的结点个数
5星 · 资源好评率100%
计算二叉树的结点个数可以通过递归实现,具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点结构体
typedef struct Node {
int data;
struct Node *left;
struct Node *right;
} Node;
// 创建二叉树结点
Node *createNode(int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// 计算二叉树结点个数
int countNodes(Node *root) {
if (root == NULL) {
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
int main() {
// 构造一棵二叉树
Node *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
int count = countNodes(root);
printf("The number of nodes in the binary tree is: %d\n", count);
return 0;
}
```
运行上述代码,输出结果为:
```
The number of nodes in the binary tree is: 5
```
阅读全文