7-5 二叉树建立2
分数 100
全屏浏览题目
切换布局
作者 吴敏华
单位 首都师范大学
已知非空的二叉树的先序序列和中序序列,建立这棵二叉树的二叉链表,输出后序序列并计算二叉树中左子树的结点个数。假设树的结点个数不超过26个。
输入格式:
输入共二行,分别给出非空的二叉树的先序序列和中序序列。
输出格式:
输出也是二行,第一行输出二叉树的后序序列,第二行输出二叉树中左子树的结点个数。
输入样例:
ABCDEGF
CBEGDFA
输出样例:
CGEFDBA
6
CODE
注:这里结点我就懒得释放了
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;
int CreateTree(BiTree& T, string PreList, string InList)
{
if (!PreList.empty())
{
char c = PreList[0];
PreList = PreList.erase(0,1);
int index = InList.find(c); //从0开始
T = new BiTNode;
T->data = c;
string PreList1;
string PreList2;
for (auto i : PreList)
{
for (auto j : InList.substr(0, index))
{
if (i == j)
{
PreList1 += i;
}
}
}
for (auto i : PreList)
{
for (auto j : InList.substr(index+1, InList.length()-index-1))
{
if (i == j)
{
PreList2 += i;
}
}
}
CreateTree(T->lchild, PreList1, InList.substr(0, index));
CreateTree(T->rchild, PreList2, InList.substr(index + 1, InList.length() - index - 1));
return 1;
}
T = nullptr;
return 1;
}
int PostOrderTrverse(BiTree T)
{
if (T)
{
if(PostOrderTrverse(T->lchild))
if (PostOrderTrverse(T->rchild))
{
cout << T->data;
return 1;
}
return 0;
}
else
{
return 1;
}
}
int main()
{
string PreList;
string InList;
BiTree T;
cin >> PreList >> InList;
CreateTree(T, PreList, InList);
PostOrderTrverse(T);
int index = InList.find(PreList[0]);
cout <<endl <<index;
return 0;
}