假设二叉树用二叉链表存储,设计一个算法,求二叉树的结点个数。 c语言写
时间: 2024-02-27 12:57:50 浏览: 93
下面是求二叉树结点个数的 C 语言实现代码:
```
#include <stdio.h>
#include <stdlib.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int countNodes(struct TreeNode* root) {
if(root == NULL) {
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
int main() {
// 构建二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->left->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->left->val = 4;
root->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->right->val = 5;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 6;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 7;
// 求二叉树结点个数
int count = countNodes(root);
printf("count: %d\n", count);
return 0;
}
```
这里使用了递归的方式,如果当前节点为 NULL 则返回 0,否则递归调用左右子树的结点个数并加上当前节点返回。
阅读全文