zoukankan      html  css  js  c++  java
  • 数据结构期末复习——还原二叉树(根据先序和中序遍历输出先序遍历)

    #include<iostream>
    #include<cstdio>
    #include<queue>
    #include<string>
    #include<algorithm>
    #include<vector>
    #include<cstring>
    #include<sstream>
    #include<cmath>
    using namespace std;
    const int maxn = 100000;
    char pre[maxn];     /**先序遍历后对应的串*/
    char ino[maxn];     /**中序遍历后对应的串*/
    //char post[maxn];    /**后序遍历后对应的串*/
    typedef struct BiNode
    {
        char data;
        BiNode *Left;
        BiNode *Right;
    }BiNode, *BiTree;
    
    BiTree build(char *pre, char *ino, int len)
    {
        if(len <= 0)
            return NULL;
        BiTree T = new BiNode;
        T->data = *pre;
        char *root = pre;
        char *p = ino;
        while(p)
        {
            //找到根节点在中序中对应的位置
            if(*p == *root)
                break;
            ++p;
        }
        //左子树的长度
        int left_len = p - ino;
        T->Left = build(pre + 1, ino, left_len);
        T->Right = build(pre + 1 + left_len, p + 1, len - left_len - 1);
        return T;
    }
    
    //后序遍历
    void postOrder(BiTree T)
    {
        if(T)
        {
            postOrder(T->Left);
            postOrder(T->Right);
            printf(" %c", T->data);
        }
    }
    
    
    int main()
    {
        /**N指二叉树节点的个数*/
        int N;
        scanf("%d %s %s", &N, pre, ino);
        BiTree T = build(pre, ino, N);
        printf("postorder:");
        postOrder(T);
        printf("
    ");
    }
    
    

    参考博客:https://blog.csdn.net/qq_37708702/article/details/79644068

  • 相关阅读:
    tyvj1117 拯救ice-cream
    codevs3410 别墅房间
    codevs1099 字串变换
    codevs1226 倒水问题
    codevs2449 骑士精神
    codevs1225 八数码难题
    Wikioi 3776 生活大爆炸版石头剪子布
    codevs1197 Vigenère密码
    枚举 + exgcd
    C++ 排序引用的优化
  • 原文地址:https://www.cnblogs.com/KeepZ/p/11918704.html
Copyright © 2011-2022 走看看