当前位置:   article > 正文

图解!后序和中序遍历创建二叉树_根据中序遍历和后序遍历画出二叉树

根据中序遍历和后序遍历画出二叉树

后序和中序遍历创建二叉树

核心思路:由后序确定根,由中序遍历确定左、右子树

  1. 假定给出中序遍历:DBEGACHFI

  2. 后序遍历:DGEBHIFCA

  3. 那么我们由后序遍历可以知道这个二叉树的根为A(后序遍历的最后一个点肯定为这个二叉树的根)

  4. 由中序遍历得知DBEG A CHFI,A的左子树为DBEG,右子树为CHFI

  5. 那么问题是不是由

    中序遍历:DBEGACHFI
    后序遍历:DGEBHIFCA

    转化为

    • 左子树
      - 中序遍历:DBEG
      - 后序遍历:DGEB
    • 右子树
      - 中序遍历:CHFI
      - 后序遍历:HIFC
      最后疯狂递归!直到不能递归!

    是不是有点思路了?接下来看我画的图理解一下吧

图解思路

最终结果

代码实现

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;

struct node
{
    char data;
    node *lchild, *rchild;
};

node *CreateBT2(char *post /*指向后序序列开头的指针*/, char *in /*指向中序序列开头的指针*/, int n)
{

    char r, *p;

    int k;

    if (n <= 0 || post == nullptr || in == nullptr) //代码鲁棒性,细节必须注意
        return nullptr;

    r = *(post + n - 1);
    node *b = (node *)malloc(sizeof(node));
    b->data = r; //我们要创建的树根节点建立好了

    for (p = in; p < in + n; ++p)
        if (*p == r)
            break;

    k = p - in; //k是左子树节点数

    b->lchild = CreateBT2(post, in, k); //这两个语句最关键
    b->rchild = CreateBT2(post + k, p + 1, n - k - 1);

    return b;
}

/****************打印各节点***********************/
int first_flag = 0;
void layerOrder(node *root)
{
    queue<node *> ans;
    ans.push(root);
    while (!ans.empty())
    {
        node *tmp = ans.front();
        ans.pop();
        if (first_flag != 0)
        {
            cout << " ";
        }
        cout << tmp->data;
        first_flag = 1;
        if (tmp->lchild != NULL)
            ans.push(tmp->lchild);
        if (tmp->rchild != NULL)
            ans.push(tmp->rchild);
    }
}

int main()
{
    char str1[40] = {0};
    char str2[40] = {0};
    printf("请输入后序序列\n");
    scanf("%s", str1);

    int len1 = 0,i=0;
    while(str1[i++]!='\0')len1++;
    printf("请输入中序序列\n");
    scanf("%s", str2);

    int len2 = 0;
    i=0;
    while(str2[i++]!='\0')len2++;
    
    if(len1!=len2)
        printf("您的输入不合法!\n");
        
    node *root = CreateBT2(str1, str2, len1);

    layerOrder(root);
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84

如果题目改成由前序遍历和中序遍历求出二叉树,是不是能做了呢?

核心:一定要有中序遍历(确定左右子树)才能求出二叉树,即只有前序、后序遍历求不出二叉树


2020年5月15日更


这是我第一次尝试自己画图,大家觉得还可以可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.gitee.io

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/465199
推荐阅读
相关标签
  

闽ICP备14008679号