前序+中序 = 二叉树(先序、中序、后序、层次遍历)

内心OS:我靠啊!!!我就是偷了一下!!!把先序遍历的代码COPY了两份,改成了中序和后序遍历。万万没想到啊!我忘了修改函数中递归函数的名字!!!找这个BUG花了我三个小时~~我哭啊~~,我还以为我的知识体系坍塌了呢?!!~

总结,这是一道模板题,要先记住大体流程,然后反复练习。

输入格式:

第一行给出结点个数 N(1<=N<= 50)

第二行给出先序序列,共N个整数

第三行给出后序序列,共N个整数

输出格式:

第一行给出先序遍历结果;

第二行给出中序遍历结果;

第三行给出后续遍历结果;

第四行给出层次遍历结果。

输入样例:

7
4 1 3 2 6 5 7
1 2 3 4 5 6 7

输出样例:

4 1 3 2 6 5 7
1 2 3 4 5 6 7
2 3 1 5 7 6 4
4 1 6 3 5 7 2

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

const int maxn = 100;
int pre[maxn],in[maxn];//先序、中序
int n;                //结点个数
struct Node {
    int data;
    Node* lchild;
    Node* rchild;
};

//当前二叉树的 先序区间[preL,preR], 后序区间[inL,inR]
Node* create(int preL,int preR,int inL,int inR) {
    //第一步,确定递归边界
    if(preL > preR)     return NULL;
    //第二步,保存当前根结点
    Node* root = new Node;
    root->data = pre[preL];
    //第三步,用根结点划分中序
    int k,leftNum;
    for(k = inL; k <= inR; ++k)
        if(in[k] == pre[preL]) break;
    leftNum = k - inL;//当前根节点左子树的结点个数
    //第四步,确定左子树的后序、中序, 右子树的后序,中序
    root->lchild = create(preL+1,preL+leftNum,inL,k-1);
    root->rchild = create(preL+leftNum+1,preR,k+1,inR);
    return root;
}

int num = 0;         //已经访问结点个数
//先序遍历二叉树
void preorder(Node* root) {
    if(root == NULL) return ;//递归边界
    if(num > 0) printf(" ");
    cout<<root->data;
    num++;
    preorder(root->lchild);//访问左子树,两个选择分支
    preorder(root->rchild);//访问右子树
}
//中序遍历二叉树
void inorder(Node* root) {
    if(root == NULL) return ;//递归边界
    inorder(root->lchild);//访问左子树,两个选择分支
    if(num > 0) printf(" ");
    cout<<root->data;
    num++;
    inorder(root->rchild);//访问右子树
}
//后序序遍历二叉树
void postorder(Node* root) {
    if(root == NULL) return ;//递归边界
    postorder(root->lchild);//访问左子树,两个选择分支
    postorder(root->rchild);//访问右子树
    if(num > 0) printf(" ");
    cout<<root->data;
    num++;
}
//层次遍历
void BFS(Node *root) {
    queue<Node*> que;//第一步,定义队列,结点入队
    que.push(root);
    while(!que.empty()) { //第二步,队列非空
        Node* top = que.front();//第三步,访问队头元素,并出队
        que.pop();
        if(num > 0) printf(" ");
        cout<<top->data;
        num++;
        //第四步,下一层元素入队(左、右孩子入队)
        if(top->lchild != NULL) que.push(top->lchild);
        if(top->rchild != NULL) que.push(top->rchild);
    }
}
int main() {
    cin>>n;
    for(int i = 0; i < n; ++i)
        cin>>pre[i];
    for(int i = 0; i < n; ++i)
        cin>>in[i];
    Node* root = create(0,n-1,0,n-1);//先序+中序重建二叉树
    preorder(root);//先序遍历
    printf("\n");
    num = 0;
    inorder(root);//中序遍历 
    printf("\n");
    num = 0;
    postorder(root);//后序遍历 
    printf("\n");
    num = 0;
    BFS(root);    //层次遍历
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/keep23456/p/12380996.html