通过先序和中序创建二叉树

#include"iostream"
#include"queue"
using namespace std;
int x[1000],z[1000];
struct Tree{
    int data;
    Tree *left,*right;
};
void xzCreate(Tree* &t,int xl,int zl,int len){        //xl:先序起始下标,zl:中序起始下标,len:数组长度
    //cout<<"zl:"<<zl<<ends<<"xl:"<<xl<<ends<<"len:"<<len<<endl;
    if(len == 1){
        t = new Tree;
        t->data = z[zl];
        t->left = NULL;
        t->right = NULL;
        return ;
    }
    for(int i = 0;z[i + zl] != x[xl];i++);        //首先在中序中找到根结点,先序第一个结点就是根结点,所以有z[i + zl] != x[xl]
    if(i >= len){    //遍历完数组还没找到根结点,就是输入错误直接返回
        return ;
    }
    //创建根节点
    t = new Tree;
    t->data = z[i + zl];
    t->left = NULL;
    t->right = NULL;

    int lenl = i;            //左子树长度就是i遍历的长度
    int lenr = len - lenl - 1;        //右子树长度为 : 总长度 - 左子树长度 - 根结点
                            //中序的左子树起点从最左开始,所以还是它本身
    xl = xl + 1;            //先序中:左子树起点 = 右子树起点 + 根结点,  跳过根节点即是左子树起点
    int zr = lenl + zl + 1;    //中序中:右子树起点 = 左子树起点 + 左子树长度 + 根结点
    int xr = xl + lenl;        //先序中:右子树起点 = 左子树起点 + 左子树长度
    //cout<<"lenl:"<<lenl<<ends<<"lenr:"<<lenr<<ends<<"zl:"<<zl<<ends<<"xl:"<<xl<<ends<<"zr:"<<zr<<ends<<"xr:"<<xr<<endl;
    //递归建树
    if(lenl != 0){
        xzCreate(t->left,xl,zl,lenl);
    }
    if(lenr != 0){
        xzCreate(t->right,xr,zr,lenr);
    }
}

void show(Tree* &t){
    if(t){
        cout<<t->data<<ends;
        show(t->left);
        show(t->right);
    }
}
//层次遍历
void sqshow(Tree *t){
    queue<Tree*> q;
    Tree *p = t;
    q.push(p);
    while(!q.empty()){
        p = q.front();
        cout<<p->data<<ends;
        if(p->left){
            q.push(p->left);
        }
        if(p->right){
            q.push(p->right);
        }
        q.pop();
    }
    cout<<endl;
}

int main(){
    Tree *t;
    int num = 7;
    for(int i = 0;i < num;i++){
        cin>>x[i];
    }
    for(i = 0;i < num;i++){
        cin>>z[i];
    }
    xzCreate(t,0,0,num);
    sqshow(t);
    return 0;
}

/*
1 2 4 5 3 6 7
4 2 5 1 6 3 7

*/
原文地址:https://www.cnblogs.com/oleolema/p/9078051.html