/*********由前序,中序遍历得到后序遍历*************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
struct TreeNode {
struct TreeNode* left;
struct TreeNode* right;
char elem;
};
void BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
if (length == 0) return;
TreeNode* node = new TreeNode;
node->elem = *preorder;
int rootIndex = 0;
for (;rootIndex < length;rootIndex++)
if (inorder[rootIndex] == *preorder) break;
BinaryTreeFromOrderings(inorder, preorder + 1, rootIndex);
BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
cout << node->elem;
return;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
char *pre = "GDAFEMHZ";
char *in = "ADEFGHMZ";
BinaryTreeFromOrderings(in, pre, 8);
cout << endl;
//Result is:AEFDHZMG
return 0;
}
二叉树——前序、中序遍历得后序遍历
最新推荐文章于 2020-12-09 17:08:48 发布