思路
要求: 读入abcdef,按照生成一棵层序遍历结果相同的树
思路:
- 依次读入每个字符,为每个字符创建一个树结点;
- 读入第一个结点时,树为空,可以直接让第一个结点作为树根,将当前结点作为第一个待插入的结点,存储到队列中;
- 读入第二个结点时,待插入结点的左子树为空,将该结点插入左子树,并将当前结点存储到队列中,作为下一个待插入结点;
- 读入第三个结点,待插入结点的左子树不为空,右子树为空,将该节点插入右子树,并将当前结点存储到队列中,当前待插入结点已满,更新待插入结点;
- ……
流程图
代码实现
#include <iostream>
using namespace std;
typedef struct biTNode {
char data;
struct biTNode *lChild;
struct biTNode *rChild;
} biTNode, *biTree;
typedef struct lQNode {
biTNode *btn;
struct lQNode *next;
} lQNode, *lQueue;
int main()
{
biTree tree = NULL;
biTNode *newBTNode;
lQueue lQHead;
lQNode *lQTail, *pcur, *newLQNode;
char c;
while (scanf("%c", &c)) {
if (c == '\n') break;
// calloc申请空间的大小为 1*sizeof()
// 使用calloc申请空间会将空间内容都初始化为0,减少了将左右子树置空的操作
newBTNode = (biTNode *) calloc(1, sizeof(biTNode));
newBTNode->data = c;
newLQNode = (lQNode *) calloc(1, sizeof(lQNode));
newLQNode->btn = newBTNode;
if (tree == NULL) {
tree = newBTNode;
lQHead = newLQNode;
lQTail = newLQNode;
pcur = newLQNode;
continue;
} else {
lQTail->next = newLQNode;
lQTail = newLQNode;
}
if (pcur->btn->lChild == NULL) {
pcur->btn->lChild = newBTNode;
} else if (pcur->btn->rChild == NULL) {
pcur->btn->rChild = newBTNode;
pcur = pcur->next;
}
}
return 0;
}
王道C语言