#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* aftorder, int length)
{
if (length == 0) return;
TreeNode* node = new TreeNode;
node->elem = *(aftorder+length-1);
cout << node->elem;
int rootIndex = 0;
for (;rootIndex < length;rootIndex++)
if (inorder[rootIndex] == *(aftorder + length - 1)) break;
BinaryTreeFromOrderings(inorder, aftorder, rootIndex);
BinaryTreeFromOrderings(inorder + rootIndex + 1, aftorder + rootIndex, length - (rootIndex + 1));
return;
}
int main()
{
char *aft = "AEFDHZMG";
char *in = "ADEFGHMZ";
BinaryTreeFromOrderings(in, aft, 8);
cout << endl;
//Result is:GDAFEMHZ
return 0;
}
二叉树——中序、后序遍历得先序遍历
最新推荐文章于 2024-06-27 19:32:22 发布