Skip to content

Instantly share code, notes, and snippets.

@Cee
Created September 24, 2014 06:12
Show Gist options
  • Save Cee/d0161bec443071024b58 to your computer and use it in GitHub Desktop.
Save Cee/d0161bec443071024b58 to your computer and use it in GitHub Desktop.
Tree
#include <iostream>
#include <cstring>
using namespace std;
char pre[100] = "zWbTghHV3oPp8LFGuAfn01rmwxJ7eiQYZ25vKqk9yCBNDU4lcMIEaOj6SRXsdt"; //前序序列
char mid[100] = "TbHVh3ogPWFLuAfGrm1xJ7we0iQYnZ8Kvqk9y5CNBD24UlcpIEMaj6SROXsdzt"; //中序序列
char post[100] = "TVHo3hPgbFfAumr7Jxew1YQi0ZnGLKy9kqvNDBC54clU28EIRS6jdsXOaMpWtz"; //后序序列
typedef struct _Node
{
char v;
struct _Node *left;
struct _Node *right;
int height;
}Node, *PNode;
void PostTravelTree(PNode pn, int height); //树的后序递归遍历
void PreTravelTree(PNode pn, int height); //树的前序递归遍历
void PreMidCreateTree(PNode &pn, int i, int j, int len); //利用前序中序序列创建树
void PostMidCreateTree(PNode &pn, int i, int j, int len); //利用后序中序序列创建树
int Position(char c); //确定c在中序序列mid中的下标,假设树的各个节点的值各不相同
int main()
{
PNode root1 = NULL, root2= NULL;
PreMidCreateTree(root1, 0, 0, strlen(mid));
PostTravelTree(root1, 0); cout<<endl; cout<<endl; cout<<endl;
PostMidCreateTree(root2, strlen(post)-1, 0, strlen(mid));
PreTravelTree(root2, 0); cout<<endl;
return 0;
}
int Position(char c)
{
return strchr(mid,c)-mid;
}
/* 利用前序中序序列创建树,参考了http://hi.baidu.com/sulipol/blog/item/f01a20011dcce31a738b6524.html
*的实现,代码十分简洁,竟然只有短短的"令人发指"的8行,递归实在太彪悍了!!!!!!!!!!!!!!!!!!!!!
* i: 子树的前序序列字符串的首字符在pre[]中的下标
* j: 子树的中序序列字符串的首字符在mid[]中的下标
* len: 子树的字符串序列的长度
*/
void PreMidCreateTree(PNode &pn, int i, int j, int len)
{
if(len <= 0)
return;
pn = new Node;
pn->v = pre[i];
int m = Position(pre[i]);
PreMidCreateTree(pn->left, i+1, j, m-j); //m-j为左子树字符串长度
PreMidCreateTree(pn->right, i+(m-j)+1, m+1, len-1-(m-j)); //len-1-(m-j)为右子树字符串长度
}
/* 利用后序中序序列创建树
* i: 子树的后序序列字符串的尾字符在post[]中的下标
* j: 子树的中序序列字符串的首字符在mid[]中的下标
* len: 子树的字符串序列的长度
*/
void PostMidCreateTree(PNode &pn, int i, int j, int len)
{
if(len <= 0)
return;
pn = new Node;
pn->v = post[i];
int m = Position(post[i]);
PostMidCreateTree(pn->left, i-1-(len-1-(m-j)), j, m-j);//注意参数:m-j左子树的长度,len-1-(m-j)右子树的长度
PostMidCreateTree(pn->right, i-1, m+1, len-1-(m-j));
}
void PostTravelTree(PNode pn, int height) //后序递归遍历
{
if(pn)
{
// printf("%d\n", height);
PostTravelTree(pn->left, height+1);
PostTravelTree(pn->right, height+1);
cout<<height<<" "<<pn->v<<"\n ";
}
}
void PreTravelTree(PNode pn, int height) //前序递归遍历
{
if(pn)
{
// pn->height = height;
cout<<height<<" "<<pn->v<<"\n ";
PreTravelTree(pn->left, height+1);
PreTravelTree(pn->right, height+1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment