二叉树·中序+前/后序遍历建树+前/中/后序遍历(链表)


还是先推荐一篇博客

很刺激而nice的东西


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

typedef struct Binary_Tree{
    char data;
    struct Binary_Tree* left;
    struct Binary_Tree* right;
}*BT,BTree;

char pre[50] = "ABDHLEKCFG";        //前序序列
char mid[50] = "HLDBEKAFCG";        //中序序列
char post[50] = "LHDKEBFGCA";        //后序序列

int Position(char s) {
    return strchr(mid,s)-mid;
//    int i;
//    int len = strlen(mid);
//    for (i = 0; i < len; i++) {
//        if (s == mid[i]) {;
//            return i - 1;
//        }
//    }
}

BT PreMidCreateTree(BT root, int i, int j, int len) { //len树及其子树结点个数
                                                      //i是在先序遍历中的起始位置(下标)
                                                      //j是在中序遍历中的起始位置
    if (len <= 0) {
        return NULL;                                  //之前写成了return root;
                                                      //是不对的,在不能建成树的时候应该返回空指针表示此处没有节点
    }
    //else {
        root = (BT) malloc(sizeof(BTree));
        int pos = Position(pre[i]);
        root -> data = pre[i];
        root -> left = PreMidCreateTree(root -> left, i+1, j, pos-j);
        root -> right = PreMidCreateTree(root -> right, i + (pos - j) + 1, pos + 1, len - 1 - (pos - j));
    //}
    return root;
}

BT PostMidCreateTree(BT root, int i, int j, int len)
{
     if(len <= 0)
         return NULL;
     root = (BT) malloc(sizeof(BTree));
     root -> data = post[i];
     int m = Position(post[i]);
     PostMidCreateTree(pn->left, i-1-(len-1-(m-j)), j, m-j);//注意参数:m-j左子树的长度,len-1-(m-j)右子树的长度
     PostMidCreateTree(pn->right, i-1, m+1, len-1-(m-j));
     return root;
}


void Post_print(BT root){
    if (root){
        Post_print(root -> left);
        Post_print(root -> right);
        printf("%c ", root -> data);
    }
}

void Pre_print(BT root){
    if (root){
        printf("%c ", root -> data);
        Pre_print(root -> left);
        Pre_print(root -> right);
    }
}

void Mid_print(BT root){
    if (root){
        Mid_print(root -> left);
        printf("%c ", root -> data);
        Mid_print(root -> right);
       
    }
}

int main() {
    BT root = NULL;
    root = PreMidCreateTree(root, 0, 0, strlen(mid));
    Post_print(root);
    puts("hkjhkj");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值