EchoDemo's Blogs

由中序和后序序列输出先序序列

先由二叉树的中序序列和后序序列重建这棵二叉树,然后再输出二叉树的先序序列。由后序序列可以得到二叉树的根节点,再在中序序列中找到此根节点即可区分出左子树和右子树的范围,递归以上步骤即可重建二叉树。完整代码如下:

#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
using namespace std;

struct node {//二叉树的存储结构
    int data;//数据域
    node* lchild;//指向左子树根节点的指针
    node* rchild;//指向右子树根节点的指针
};

node* create(int in[], int post[], int inL, int inR, int postL, int postR) {//根据中序序列和后序序列重建二叉树
    if (inL>inR) return NULL;//如果后序序列长度小于等于0,直接返回空
    node* root = new node;//新建一个节点,用来存放当前二叉树的根节点
    root->data = post[postR];//新建节点的数据域为根节点的值
    int k;
    for (k = inL;k <= inR;k++) {
        if (in[k] == post[postR]) {//在中序序列中找到根节点
            break;
        }
    }
    int num = k - inL;//左子树的节点个数

    //左子树的后序序列区间为[postL,postL+num-1],中序序列区间为[inL,k-1]
    root->lchild = create(in, post, inL, k - 1, postL, postL + num - 1);//返回左子树的根节点地址,赋值给root的左指针

    //右子树的后序序列区间为[postL+num,postR-1],中序序列区间为[k+1,inR]
    root->rchild = create(in, post, k + 1, inR, postL + num, postR - 1);//返回右子树的根节点地址,赋值给root的右指针

    return root;//返回根节点地址
}

void preorder(node* root) {//先序遍历二叉树
    if (root == NULL) {
        return;//递归边界
    }
    cout<<root->data;//访问根节点
    preorder(root->lchild);//访问左子树
    preorder(root->rchild);//访问右子树
}

int main() {
    int n;
    cin >> n;//输入二叉树的节点个数
    int *in = new int[n];//new一个变长的int型数组
    int *post = new int[n];
    for (int i = 0;i < n;i++) {//输入中序序列
        cin >> in[i];
    }
    for (int i = 0;i < n;i++) {//输入后序序列
        cin >> post[i];
    }
    int inL = 0,postL = 0, inR = n - 1, postR = n - 1;
    preorder(create(in, post, inL, inR, postL, postR));
    delete[] post;//释放内存
    delete[] in;
    system("pause");
    return 0;
}
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------