二叉树叶子结点构建为双链表(C语言)

输入样例:
1248009005003600700
0

输出样例:
89567

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 100
#define LNode BiTree

typedef struct BiTNode {
    char data;
    struct BiTNode *left, *right;
} BiTNode, *BiTree;

void CreateBiTree(BiTree *T, char *str, int *cursor);

void DestroyBiTree(BiTree T);

void LinkLeafNode(LNode T, BiTNode **last_leaf);

void ListShow(LNode T);

void ListRestore(LNode T);

int main() {
    char str[MAX_SIZE];
    while (scanf("%s", str) && str[0] != 48) {
        BiTree T = NULL;
        int cursor = 0;
        LNode head_node = (BiTree) malloc(sizeof(BiTNode));
        LNode head = head_node;

        CreateBiTree(&T, str, &cursor);
        LinkLeafNode(T, &head_node);
        ListShow(head->right);
        ListRestore(head);//leave the left and right pointers of leaf nodes empty
        DestroyBiTree(T);
        free(head);
    }

    return 0;
}

void CreateBiTree(BiTree *T, char *str, int *cursor) {
    if (str[*cursor] == 48) {
        *T = NULL;
    } else {
        *T = (BiTree) malloc(sizeof(BiTNode));
        (*T)->data = str[*cursor];

        (*cursor)++;
        CreateBiTree(&((*T)->left), str, cursor);
        (*cursor)++;
        CreateBiTree(&((*T)->right), str, cursor);
    }
}

void DestroyBiTree(BiTree T) {
    if (T) {
        DestroyBiTree(T->left);
        DestroyBiTree(T->right);
        free(T);
    }
}

void LinkLeafNode(LNode T, BiTNode **last_leaf) {
    if (T) {
        if (!T->left && !T->right) {//T is a leaf node
            (*last_leaf)->right = T;
            T->left = *last_leaf;
            *last_leaf = T;
        } else {
            LinkLeafNode(T->left, last_leaf);
            LinkLeafNode(T->right, last_leaf);
        }
    }
}

void ListShow(LNode T) {
    while (T) {
        printf("%c", T->data);
        T = T->right;
    }
}

void ListRestore(LNode T) {
    LNode next;
    while (T) {
        next = T->right;
        T->right = NULL;
        T->left = NULL;
        T = next;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值