数据结构经常会考:由二叉树前序+中序 判断后序 或 后序+中序判断前序。
下面编程实现作为练习:
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Node{
char data;
Node *pleft;
Node *pright;
Node():pleft(NULL),pright(NULL){}
};
typedef Node* pNode;
class bTree{
public:
bTree(char* pr, char* mid, char* post):m_pr(pr),m_mid(mid),m_post(post),m_Btree(NULL){};
pNode m_Btree;
void pr_mid(pNode& tree,int i,int j,int len);//已知前序和中序
void post_mid(pNode& tree, int i, int j, int len);//已知后序和中序
static void print_post(pNode node){
if (!node)
return;
print_post(node->pleft);
print_post(node->pright);
cout << node->data;
}
static void print_pr(pNode node){
if (!node)
return;
cout << node->data;
print_pr(node->pleft);
print_pr(node->pright);
}
static void free(pNode node){
if (!node)
return;
free(node->pleft);
free(node->pright);
delete node;
}
void print_tree(){
queue<pNode> s1,s2;
s1.push(m_Btree);
while (!s1.empty() || !s2.empty()){
if (s1.empty()){
while (!s2.empty()){
pNode temp = s2.front();
s2.pop();
cout << temp->data;
if (temp->pleft)
s1.push(temp->pleft);
if (temp->pright)
s1.push(temp->pright);
}
}
else{
while (!s1.empty()){
pNode temp = s1.front();
s1.pop();
cout << temp->data;
if (temp->pleft)
s2.push(temp->pleft);
if (temp->pright)
s2.push(temp->pright);
}
}
cout << endl;
}
}
private:
int loc_in_mid(char ch){
return string(m_mid, m_mid + strlen(m_mid)).find_first_of(ch);
}
char *m_pr;//前序
char *m_mid;//中序
char *m_post;//后序
};
void bTree::pr_mid(pNode& tree, int i, int j, int len){//i为子树第一个元素在前序的位置,j为子树第一个元素在中序的位置,len为序列长度
if (len == 0)
return;
tree = new Node;
tree->data = m_pr[i];
int loc = loc_in_mid(tree->data);
pr_mid(tree->pleft, i + 1, j, loc - j);
pr_mid(tree->pright, i + (loc - j) + 1, loc + 1, len - (loc - j + 1));
}
void bTree::post_mid(pNode& tree, int i, int j, int len){//i为子树第一个元素在后序的位置,j为子树第一个元素在中序的位置,len为序列长度
if (len == 0)
return;
tree = new Node;
tree->data = m_post[i+len-1];
int loc = loc_in_mid(tree->data);
post_mid(tree->pleft, i, j, loc - j);
post_mid(tree->pright, i + (loc - j), loc + 1, len - (loc - j + 1));
}
int main(){
char *pr="ABDHLEKCFG";
char *mid = "HLDBEKAFCG";
char *post = "LHDKEBFGCA";
bTree bt(pr,mid,NULL);//已知前序,中序
bt.pr_mid(bt.m_Btree,0,0,strlen(pr));
bt.print_tree();
cout << "Post: ";
bTree::print_post(bt.m_Btree);
cout << endl;
bTree::free(bt.m_Btree);
bt = bTree(NULL, mid, post);//已知后序,中序
bt.post_mid(bt.m_Btree,0, 0, strlen(pr));
cout << "Pr: ";
bTree::print_pr(bt.m_Btree);
bTree::free(bt.m_Btree);
}