赞
踩
假定给出中序遍历:DBEGACHFI
后序遍历:DGEBHIFCA
那么我们由后序遍历可以知道这个二叉树的根为A(后序遍历的最后一个点肯定为这个二叉树的根)
由中序遍历得知DBEG A CHFI,A的左子树为DBEG,右子树为CHFI
那么问题是不是由
中序遍历: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;
}
2020年5月15日更
这是我第一次尝试自己画图,大家觉得还可以可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.gitee.io
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。