2024王道408数据结构 P143 T8
思考过程
- 首先题目的意思非常简单明了,就是让我们找二叉树中度为2的结点,也就是既有左子树又有右子树的结点。那我们只需要在代码里判断如果该结点有左子树就入队,同时如果该结点有右子树就计数器+1,并且入队,非常简单。
- 这题就没什么难理解的点了,就是在层次遍历的过程中加一层判断就可以了。
举个例子
- 首先我们需要一个num变量用来存放双分支结点的个数,还需要一个指针p用来指向队首元素,我们用一个辅助队列来帮我们实现层次遍历。假设二叉树长这个样子
- 开始时指针p指向根结点A,先把结点A入队,当队列不为空时出队,出队之后开始判断
- 当该结点A有左子树时将左子树入队,在例子中就是结点B,紧接着再判断有无右子树,如果有的话把右子树入队,也就是结点C,此时说明该结点有左右子树,num++。
- 如果该结点没有左子树的话就去判断右子树,右子树存在的话就入队右子树,不动num值就好了。
完整代码
//
// Created by 黎圣 on 2023/8/13.
//
#include "iostream"
#define MAX 15
struct TreeNode
{
char data;
struct TreeNode *lchild, *rchild;
};
struct Queue
{
struct TreeNode *data[MAX];
int f, r, tag;
};
bool QueueEmpty(Queue &q)
{
if (q.r == q.f && q.tag == 0)
return true;
return false;
}
bool QueueOverflow(Queue &q)
{
if (q.r == q.f && q.tag == 1)
return true;
return false;
}
bool EnQueue(Queue &q, struct TreeNode *&p)
{
if (QueueOverflow(q))
{
printf("队满,入队失败\n");
return false;
}
else
{
q.data[q.r] = p;
q.r = (q.r + 1) % MAX;
q.tag = 1;
return true;
}
}
bool DeQueue(Queue &q, struct TreeNode *&p)
{
if (QueueEmpty(q))
{
printf("队空,出队失败\n");
return false;
}
else
{
p = q.data[q.f];
q.f = (q.f + 1) % MAX;
q.tag = 0;
return true;
}
}
void CreateTree(struct TreeNode *&t)
{
char ch = getchar();
if (ch == '#')
t = NULL;
else
{
t = (struct TreeNode*)malloc(sizeof(struct TreeNode));
t->data = ch;
t->lchild = NULL;
t->rchild = NULL;
CreateTree(t->lchild);
CreateTree(t->rchild);
}
}
int num(struct TreeNode *t)
{
Queue q;
q.r = q.f = q.tag = 0;
struct TreeNode *p = t;
EnQueue(q, p);
int num = 0;
while (!QueueEmpty(q))
{
DeQueue(q, p);
if (p->lchild)
{
EnQueue(q, p->lchild);
if (p->rchild)
{
EnQueue(q, p->rchild);
num++;
}
}
else
{
if (p->rchild)
EnQueue(q, p->rchild);
}
}
return num;
}
void display(struct TreeNode *t)
{
if (t)
{
printf("%c ", t->data);
display(t->lchild);
display(t->rchild);
}
}
int main()
{
struct TreeNode *t;
CreateTree(t);
//ABD###CE##F## 2
//ABD##E##CF##G## 3
display(t);
printf("\n%d", num(t));
return 0;
}
这题确实比较简单没什么好说的,这次就不感谢小金鱼了因为是我自己写出来的🐶