c语言,设计一个算法,求二叉树第k层的结点个数。完整代码
时间: 2023-06-10 17:03:03 浏览: 117
C语言 求一个二叉树中位于先序序列中第k个位置的结点的值.doc
以下是C语言设计的算法,用于求二叉树第k层的结点个数:
```
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node *left;
struct node *right;
int value;
};
int countNodesAtLevelK(struct node *root, int k){
if(root == NULL){
return 0;
}
else if(k == 1){
return 1;
}
else{
return countNodesAtLevelK(root->left, k-1) + countNodesAtLevelK(root->right, k-1);
}
}
int main(){
struct node *root = (struct node*)malloc(sizeof(struct node));
root->value = 1;
root->left = (struct node*)malloc(sizeof(struct node));
root->left->value = 2;
root->right = (struct node*)malloc(sizeof(struct node));
root->right->value = 3;
root->left->left = (struct node*)malloc(sizeof(struct node));
root->left->left->value = 4;
root->left->right = (struct node*)malloc(sizeof(struct node));
root->left->right->value = 5;
root->right->left = (struct node*)malloc(sizeof(struct node));
root->right->left->value = 6;
root->right->right = (struct node*)malloc(sizeof(struct node));
root->right->right->value = 7;
int k = 3;
int count = countNodesAtLevelK(root, k);
printf("The number of nodes at level %d is %d", k, count);
return 0;
}
```
在此示例中,我们创建了一个二叉树,并求出了第三层的结点数。请注意,此算法使用递归来计算二叉树的层级结点数,因此效率可能不高。
阅读全文