|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 yinda_peng 于 2023-8-22 19:47 编辑
代码:
- #include <stdio.h>
- #include <stdlib.h>
- // 定义线索二叉树结点的结构体
- typedef struct Node {
- struct Node *lchild;
- int ltag;
- char data;
- int rtag;
- struct Node *rchild;
- } Node;
- int level = 0; // 当前层数
- // 创建线索二叉树
- Node* createThreadedBinaryTree() {
- Node *p;
- char c;
- scanf("%c", &c);
- if (c == '^') { // 遇到^符号表示此分支为空
- return NULL;
- }
- p = (Node*)malloc(sizeof(Node));
- p->data = c;
- p->ltag = 0; // 初始化为0
- p->rtag = 0;
- p->lchild = createThreadedBinaryTree(); // 递归创建左子树
- p->rchild = createThreadedBinaryTree(); // 递归创建右子树
- return p;
- }
- // 中序遍历线索化二叉树(中序线索化过程)
- void inorderThreaded(Node *p, Node **pre) {
- if (p != NULL) {
- inorderThreaded(p->lchild, pre); // 递归线索化左子树
- // 处理当前结点
- if (p->lchild == NULL) { // 左孩子为空,将ltag置为1,指向前驱结点
- p->ltag = 1;
- p->lchild = *pre;
- }
-
- if (*pre != NULL && (*pre)->rchild == NULL) { // 前驱结点的右孩子为空,将rtag置为1,指向后继结点
- (*pre)->rtag = 1;
- (*pre)->rchild = p;
- }
- *pre = p;
- inorderThreaded(p->rchild, pre); // 递归线索化右子树
- }
- }
- // 打印线索二叉树图示化节点
- void printNodes(Node *root, int level) {
- if (root == NULL)
- return;
- printNodes(root->lchild, level + 1); // 先遍历左子树
- int i;
- for (i = 0; i < level; i++) {
- printf(" "); // 打印空格,表示层级
- }
- if (root->data == ' ') {
- printf("^"); // 打印^表示空节点
- } else {
- printf("%c", root->data); // 打印节点值
- }
- printf("\n");
- printNodes(root->rchild, level + 1); // 再遍历右子树
- }
- int main() {
- printf("请输入中序遍历序列(^表示为空):\n");
- Node *root = createThreadedBinaryTree();
- Node *pre = NULL; // 前驱结点初始化为空
- inorderThreaded(root, &pre);
- printf("\n打印线索二叉树节点图示化:\n");
- printNodes(root, level);
- return 0;
- }
复制代码 输入^A^没有打印任何东西:
为什么呢?哪里需要修改?
按你的输入主函数,这里root不就是NULL。
printf("请输入中序遍历序列(^表示为空):\n");
Node *root = createThreadedBinaryTree();
if(root==NULL)
{
printf("NULL\n");
}
Node* createThreadedBinaryTree() {
Node *p;
char c;
scanf("%c", &c);
if (c == '^') { // 遇到^符号表示此分支为空
return NULL;
}
|
|