二叉树有前序、中序、后序三种遍历方法,如果知道了其中两种的遍历结果,是不是就可以重建原来的二叉树呢?当然这里是有前提的,二叉树的节点不能有相同的,不然有可能无法还原!
已知前序和中序
前序遍历结果的第一个元素是原二叉树的根,接下来的是左子树和右子树的前序遍历结果。中序遍历结果中根左边的是左子树的中序遍历结果,右边的是右子树的中序遍历结果!我们可以将问题转换为两个子问题,采用递归的方法很容易求解!见11-29行代码。
已知中序和后序
后序遍历结果的最后一个元素是原二叉树的根,类似于“前序和中序”中的方法,可以转换为两个子问题求解,见31-49行代码。
已知前序和后序
遗憾的是,如果只知道前序和后序,我们是无法还原出原来的二叉树的!例如,对于前序遍历结果是ab,后序遍历结果是ba,根本无法确定b究竟是左子树还是右子树,所以无法重建出二叉树。
#include <iostream>
#include <string>
using namespace std;
struct tree {
int value;
struct tree *lchild;
struct tree *rchild;
};
struct tree *rebuild_fm(string f, string m)
{
if (f.length() > 0 && f.length() == m.length()) {
size_t pos = m.find(f[0]);
if (pos != string::npos) {
string ff, mm;
struct tree *root = new struct tree;
root->value = m[pos];
ff = f.substr(1, pos);
mm = m.substr(0, pos);
root->lchild = rebuild_fm(ff, mm);
ff = f.substr(pos+1, f.length()-pos-1);
mm = m.substr(pos+1, m.length()-pos-1);
root->rchild = rebuild_fm(ff, mm);
return root;
}
}
return 0;
}
struct tree *rebuild_ml(string m, string l)
{
if (m.length() > 0 && m.length() == l.length()) {
size_t pos = m.find(l[l.length()-1]);
if (pos != string::npos) {
string mm, ll;
struct tree *root = new struct tree;
root->value = m[pos];
mm = m.substr(0, pos);
ll = l.substr(0, pos);
root->lchild = rebuild_ml(mm, ll);
mm = m.substr(pos+1, m.length()-pos-1);
ll = l.substr(pos , l.length()-pos-1);
root->rchild = rebuild_ml(mm, ll);
return root;
}
}
return 0;
}
void print(struct tree *root)
{
if (root) {
cout << (char)root->value << endl;
print(root->lchild);
print(root->rchild);
}
}
int main()
{
print(rebuild_fm("abdcef", "dbaecf"));
print(rebuild_ml("dbaecf", "dbefca"));
return 0;
}