c语言用按层次顺序遍历二叉树的方法,统计树中具有度为1的结点数目代码
时间: 2024-02-22 07:58:01 浏览: 89
二叉树的层次遍历(c语言)
5星 · 资源好评率100%
以下是用C语言实现的按层次顺序遍历二叉树,并统计具有度为1的节点数目的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int countDegreeOneNodes(struct TreeNode* root) {
if (root == NULL) {
return 0;
}
int count = 0;
struct TreeNode* queue[1000]; // 假设二叉树的节点数不超过1000
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
struct TreeNode* node = queue[front++];
if (node->left == NULL && node->right != NULL) { // 只有右子节点
count++;
} else if (node->left != NULL && node->right == NULL) { // 只有左子节点
count++;
}
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
return count;
}
int main() {
// 构造一棵二叉树进行测试
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node1 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node2 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node3 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node4 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
node1->val = 2;
node2->val = 3;
node3->val = 4;
node4->val = 5;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = NULL;
node2->left = NULL;
node2->right = node4;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
printf("%d\n", countDegreeOneNodes(root)); // 输出2
return 0;
}
```
该方法使用一个数组模拟队列来存储每一层的节点,并依次出队并处理每个节点。具体处理方法与Java版本的代码相同。
阅读全文