题目
地址:https://pintia.cn/problem-sets/994805046380707840/exam/problems/994805069361299456
错误信息
代码内容
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int n; //二叉树结点个数
typedef struct biTreeNode { //定义二叉树结点
char key;
biTreeNode* lchild;
biTreeNode* rchild;
}biTree, * BiTree;
void creatBiTree(BiTree& T, string post, string in) //建立二叉树:根节点地址,该树后序遍历序列,该树中序遍历序列
{
if (post.length() == 0 && in.length() == 0)T = NULL;
else {
if (!(T = (biTreeNode*)malloc(sizeof(biTreeNode))))
{
exit(0);
}
T->key = post[post.size() - 1]; //当前结点键值等于后序遍历序列的最后一个值
int k = in.find(T->key, 0); //中序遍历序列中根结点key对应的下标,同时也是左子树结点个数
string inleft(in, 0, k);
string postleft(post, 0, k);
creatBiTree(T->lchild, postleft, inleft);
//右子树结点个数=中序/后序遍历序列的长度-左子树结点个数-1,即in.length()-k-1或post.length()-k-1
string inright(in, k + 1, in.length() - k - 1);
string postright(post, k, post.length() - k - 1);
creatBiTree(T->rchild, postright, inright);
}
return;
}
void FloorPrint(BiTree &T) //对二叉树层序遍历
{
BiTree temp[30];//储存二叉树的结点地址
int l = 0, r = 0; //l指向入队下标,r指向出队下标
temp[l++] = T; //记录二叉树根结点地址
while (r<l) {
cout << temp[r]->key;
if (r < n - 1)
cout << " "; //输出键值,根据情况输出空格
if (temp[r]->lchild) //让不为空的子树入队
temp[l++] = temp[r]->lchild;
if (temp[r]->rchild)
temp[l++] = temp[r]->rchild;
r++;
}
}
int main()
{
cin >> n; getchar();
string inOrder, postOrder;
char ch;
for (int i = 0; i < n; i++) { //获取后序遍历序列
cin >> ch; getchar();
postOrder += ch;
}
for (int i = 0; i < n; i++) { //获取中序遍历序列
cin >> ch; getchar();
inOrder += ch;
}
BiTree head; //创建头指针,指向二叉树的根结点
creatBiTree(head, postOrder, inOrder); //根据后序遍历序列和中序遍历序列建立二叉树
FloorPrint(head);
return 0;
}
问题
求上述代码问题所在和本题详细解答,重点是问题所在,万分感谢!