1. 根據給定的二叉樹前序和中序遍歷結果還原二叉樹;
2. 將還原的二叉樹以二叉樹形式保存在內存中;
3. 對建立的二叉樹進行後序遍歷
代碼如下:
#include <iostream>
#include <functional>
using namespace std;
/*
char str1[30]; //保存前序遍歷字符串
char str2[30]; //保存後序遍歷字符串
int loc; //靜態數組中已分配的結點個數
//因爲有多組樣例輸入,因此用loc記錄每個樣例的根結點的位置
struct Node
{
Node *lchild; //指向當前結點的左孩子
Node *rchild; //指向當前結點的右孩子
char c; //代表結點的值
}tree[51]; //用數組存儲樹的各個結點,用指針代表各結點之間的關係
//注意,指針指向的是各結點的數組地址
Node *creat() //初始化,返回的是一Node型指針
{
tree[loc].lchild = NULL;
tree[loc].rchild = NULL;
return &tree[loc++]; //樹的各結點是按分配的先後順序存放在結構數組中
//但當前結點的左右孩子關係是靠指針說明的
}
void PostOrder(Node *T) //後序遍歷,T是結構指針
{
if (T->lchild!=NULL) //後序遍歷先左孩子後右孩子最後雙親
{
PostOrder(T->lchild);
}
if (T->rchild!=NULL)
{
PostOrder(T->rchild);
}
cout << T->c; //輸出雙親結點
}
//由字符串的前序和中序遍歷得到原樹,返回原樹的根結點
Node *build(int s1, int e1, int s2, int e2) //傳入的參數是字符串的下標
{
//前序遍歷結果爲str1[s1]-str1[e1],後序遍歷結果爲str2[s2]-str2[e2]
Node *ret = creat(); //爲該樹的根結點申請空間,ret指向樹的根結點,是一個結構指針
ret->c = str1[s1];
int rootInx = 0; //根結點在中序遍歷中的位置,以此劃分遞歸階段
for (int i = s2; i <= e2; i++)
{
if (str2[i]==ret->c)
{
rootInx = i;
break;
}
}
if (rootInx!=s2) //原樹有左子樹
{
ret->lchild = build(s1 + 1, rootInx - s2 + s1, s2, rootInx - 1);
}
if (rootInx!=e2) //原樹有右子樹
{
ret->rchild = build(rootInx - s2 + s1 + 1, e1, rootInx + 1, e2);
}
return ret; //返回原樹的根結點指針
}
int main()
{
while (cin>>str1>>str2)
{
loc = 0; //初始化靜態內存空間中已經使用的結點個數
int len1 = strlen(str1);
int len2 = strlen(str2);
Node *root = build(0,len1-1,0,len2-1);
PostOrder(root);
cout << endl;
}
return 0;
}*/