以二叉链表作为二叉树的存储结构,编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数C语言
时间: 2023-06-13 09:08:32 浏览: 96
头歌数据结构二叉树的二叉链表存储及基本操作
5星 · 资源好评率100%
以下是用C语言实现二叉树层次遍历,并统计度为1结点个数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
//定义二叉树结点
typedef struct BTreeNode{
int data;
struct BTreeNode *lchild;
struct BTreeNode *rchild;
}BTreeNode, *BTree;
//定义队列结点
typedef struct Node{
BTree data;
struct Node *next;
}Node, *Queue;
//队列操作
void initQueue(Queue *Q){
*Q = (Node*)malloc(sizeof(Node));
(*Q)->next = NULL;
}
void enQueue(Queue Q, BTree node){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = node;
newNode->next = NULL;
while(Q->next != NULL) Q = Q->next;
Q->next = newNode;
}
BTree deQueue(Queue Q){
Node *p = Q->next;
BTree res = p->data;
Q->next = p->next;
free(p);
return res;
}
int isEmpty(Queue Q){
if(Q->next == NULL) return 1;
return 0;
}
//层次遍历
void levelOrder(BTree root, int *count){
Queue Q;
initQueue(&Q);
BTree p = root;
if(p) enQueue(Q, p);
while(!isEmpty(Q)){
p = deQueue(Q);
if(p->lchild){
enQueue(Q, p->lchild);
if(p->rchild == NULL) (*count)++;
}
if(p->rchild){
enQueue(Q, p->rchild);
if(p->lchild == NULL) (*count)++;
}
}
}
int main(){
//构建二叉树
BTreeNode node1 = {1, NULL, NULL};
BTreeNode node2 = {2, NULL, NULL};
BTreeNode node3 = {3, NULL, NULL};
BTreeNode node4 = {4, NULL, NULL};
BTreeNode node5 = {5, NULL, NULL};
BTreeNode node6 = {6, NULL, NULL};
BTreeNode node7 = {7, NULL, NULL};
BTreeNode node8 = {8, NULL, NULL};
node1.lchild = &node2;
node1.rchild = &node3;
node2.lchild = &node4;
node2.rchild = &node5;
node3.lchild = &node6;
node3.rchild = &node7;
node5.lchild = &node8;
int count = 0;
levelOrder(&node1, &count);
printf("度为1的结点个数为:%d\n", count);
return 0;
}
```
以上代码中,我们使用了一个队列来存储需要遍历的结点,然后依次取出队首结点进行操作,如果该结点有左子树,就将左子树结点入队,如果该结点有右子树,就将右子树结点入队,如果该结点只有一个子树,就将计数器加1。最后输出计数器的值就是度为1的结点个数。
阅读全文