使用C++实现设计求一棵二叉树中结点总数的算法并写出完整程序
时间: 2023-06-03 15:01:33 浏览: 211
以下是使用C语言实现求一棵二叉树中结点总数的算法的代码:
```
#include <stdio.h>
#include <stdlib.h>
/* 二叉树结点结构体 */
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
/* 求二叉树结点总数 */
int countNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
int main() {
/* 构建测试用例 */
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
TreeNode* node2 = (TreeNode*)malloc(sizeof(TreeNode));
node2->val = 2;
TreeNode* node3 = (TreeNode*)malloc(sizeof(TreeNode));
node3->val = 3;
root->left = node2;
root->right = node3;
TreeNode* node4 = (TreeNode*)malloc(sizeof(TreeNode));
node4->val = 4;
TreeNode* node5 = (TreeNode*)malloc(sizeof(TreeNode));
node5->val = 5;
node2->left = node4;
node2->right = node5;
TreeNode* node6 = (TreeNode*)malloc(sizeof(TreeNode));
node6->val = 6;
TreeNode* node7 = (TreeNode*)malloc(sizeof(TreeNode));
node7->val = 7;
node3->left = node6;
node3->right = node7;
/* 调用函数求结点总数 */
int count = countNodes(root);
printf("节点总数为%d\n", count);
return 0;
}
```
运行结果为:
```
节点总数为7
```
阅读全文