构建二叉树及遍历

来源:互联网 发布:windows未能启动怎么办 编辑:程序博客网 时间:2024/05/17 06:47

第一个是中序后序构造二叉树,并先序遍历,特点在后序中每一个末端值都是节点,以此在先序中查找并以此点分割左右子树,递归一下…
第二个是先序中序构造二叉树,并后序和层次遍历,特点是以先序为参照在中序查找,层次遍历最好还是使用队列吼啊….代码并不能直接用,我把两个问题搓在一起了。。。

#include<iostream>#include<string.h>#include<queue>using namespace std;struct node {    char data;    node *l, *r;};tree *creat_(int n,char *str1,char *str2) {//后序中序二叉树    struct tree *root;    int i=0;    if (n == 0)        return NULL;    root = new tree;    root->data = str2[n - 1];      cout<<root->data;    while (str1[i] != str2[n - 1])i++;    root->left = creat(i, str1, str2);    root->right = creat(n - i - 1, str1 + i + 1, str2 + i);    return root;}node *creat(char *str1, char *str2,int n) {//前序中序二叉树    if (n == 0)        return NULL;    node *tree = new node;    tree->data = *str1;    int k;    char *p;    for (p = str2; p != NULL; p++)    {        if (*p == *str1)            break;    }    k = p - str2;    tree->l = creat(str1 + 1, str2, k);    tree->r = creat(str1 + k + 1, p + 1, n - k - 1);    return tree;}void pri(node *tree) {    if (tree->l)pri(tree->l);    if (tree->r)pri(tree->r);    cout << tree->data;}void bfs(node *tree) {    queue<node*> que;    que.push(tree);    node *p = tree;    while (!que.empty()) {        cout << que.front()->data;        if(que.front()->l!=NULL)que.push(que.front()->l);        if(que.front()->r!=NULL)que.push(que.front()->r);        que.pop();    }}int main(void){    char str1[50], str2[50];    int t; cin >> t;    while (t--) {        memset(str1, 0, sizeof(str1));        memset(str2, 0, sizeof(str2));        cin >> str1 >> str2;        pri(creat( str1, str2,strlen(str1)));        cout << endl;        bfs(creat(str1, str2, strlen(str1)));        cout << endl;    }    return 0;}