由二叉树的中序后序遍历序列确定先序遍历序列

 思路:

只讲解如何通过中序后序遍历序列来构建二叉树:假设递归的过程中某部的后序序列区间为[postL,postR],中序序列的区间为[inL, inR],那么由后序序列的性质可知,后序序列的最后一个元素post[postR]即为根节点。那么,我们在中序序列中找到一个位置i,使得in[i]==post[postR],这样就找到了中序序列的根节点。那么锁子书中的节点的个数numLeft=i-inL,于是左子树的后序序列区间为[postL,postL+numLeft-1],左子树的中序序列区间为[inL, k-1]; 右子树的后序序列区间为[postL+numLeft,postR-1],右子树的中序序列区间为[i+1,inR]。

#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;

const int maxn = 50;
struct node
{
    int data;
    node* lchild;
    node* rchild;
};

int pre[maxn], in[maxn], post[maxn];
int n;

node* create(int postl, int postr, int inl, int inr);
void preorder(node* root);
int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> post[i];
    }
    for (int i = 0; i < n; i++) {
        cin >> in[i];
    }
    node* root = create(0, n-1, 0, n-1);
    preorder(root);
}

node* create(int postl, int postr, int inl, int inr) {
    
    if (postl > postr) {
        return NULL;
    }
    node* root = new node;
    root->data = post[postr];
    int i = inl;
    for (i=inl; i <= inr; i++) {
        if (in[i] == post[postr]) {
            break;
        }
    }
    int inleftnumber = i-inl;
    
    root->lchild = create(postl, postl + inleftnumber -1, inl, i -1);
    root->rchild = create(postl + inleftnumber, postr - 1, i + 1, inr);
    return root;
}

void preorder(node* root) {
    if (root == NULL) {
        return;
    }
    cout << root->data<<" ";
    preorder(root->lchild);
    preorder(root->rchild);
}

同理,根据二叉树的前序,中序,也可以确定一颗唯一的二叉树:

node* create(int preL, int preR, int inL, int inR) {
    if (preL>preR)
    {
        return NULL;
    }
    node* root = new node;
    root->data = pre[preL];
    int i;
    for (i = inL; i < inR; i++)
    {
        if (in[i]==root->data)
        {
            break;
        }
    }
    int numsleft = i - inL;
    root->lchild = create(preL + 1, preL + numsleft, inL, i - 1);
    root->rchild = create(preL + numsleft + 1, preR, i + 1, inR);
    return root;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值