- 根据前序中序确定二叉树
- 根据后序中序确定二叉树
- 根据层次中序确定二叉树
注意,根据前序和后序无法确定一棵二叉树
#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
#define ElemType char
typedef struct treeNode {
struct treeNode * lchild;
struct treeNode * rchild;
ElemType data;
}treeNode,* tree;
void preOrder(tree & t) {
if (t) {
std::cout << t->data;
preOrder(t->lchild);
preOrder(t->rchild);
}
}
void inOrder(tree & t) {
if (t) {
inOrder(t->lchild);
std::cout << t->data;
inOrder(t->rchild);
}
}
void postOrder(tree & t) {
if (t) {
postOrder(t->lchild);
postOrder(t->rchild);
std::cout << t->data;
}
}
void levelOrder(tree & t) {
queue<tree> q;
if (t) {
q.push(t);
while (!q.empty()) {
tree temp = q.front();
cout << temp->data ;
q.pop();
if (temp->lchild)
q.push(temp->lchild);
if (temp->rchild)
q.push(temp->rchild);
}
}
}
void preInCreate(string pre_str, string in_str, tree & t) {
if (!pre_str.empty()&&!in_str.empty()) {
t = (treeNode *)malloc(sizeof(treeNode));
t->data = pre_str[0];
int pos = in_str.find(pre_str[0]);
string lpstr = pre_str.substr(1, pos);
string rpstr = pre_str.substr(pos + 1, pre_str.length() - 1 - pos);
string listr = in_str.substr(0, pos);
string ristr = in_str.substr(pos + 1, in_str.length() - 1 - pos);
preInCreate(lpstr, listr, t->lchild);
preInCreate(rpstr, ristr, t->rchild);
}
else
t = NULL;
}
void postInCreate(string in_str, string post_str, tree & t) {
if (!in_str.empty() && !post_str.empty()) {
t = (treeNode*)malloc(sizeof(treeNode));
t->data = post_str[post_str.length() - 1];
int pos = in_str.find(post_str[post_str.length() - 1]);
string listr = in_str.substr(0, pos);
string ristr = in_str.substr(pos + 1, in_str.length() - 1 - pos);
string lpstr = post_str.substr(0, pos);
string rpstr = post_str.substr(pos, in_str.length() - 1 - pos);
postInCreate(listr, lpstr, t->lchild);
postInCreate(ristr, rpstr, t->rchild);
}
else
t = NULL;
}
int main() {
string pre_str;
string in_str;
string post_str;
tree t;
postInCreate(in_str, post_str, t);
preOrder(t);
cout << endl;
postInCreate(in_str, post_str, t);
inOrder(t);
cout << endl;
postInCreate(in_str, post_str, t);
postOrder(t);
cout << endl;
postInCreate(in_str, post_str, t);
levelOrder(t);
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}