1020 Tree Traversals (25 point(s))

原文地址

题意:

根据一棵二叉树的后序遍历和中序遍历来输出层序遍历结果。

分析:

首先想到的是,先根据后序和中序遍历结果来构造一颗二叉树。如何构造?一棵二叉树(子树也一样)的后序遍历的最后一个节点就是整棵树(子树)的根节点,然后可以利用这一个根节点到中序遍历中去查找,然后左边的即为左子树,右边的即为右子树。生成二叉树完了过后就简单了,利用队列的原理然后进行层序遍历。

代码:

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct node
{
    int value;
    node*left;
    node*right;
};
int N;
vector<int>postorder;
vector<int>inorder;

void handleInput()
{
    cin>>N;
    int temp;
    for(int i=0;i<N;++i)
    {
        cin>>temp;
        postorder.push_back(temp);
    }
    for(int i=0;i<N;++i)
    {
        cin>>temp;
        inorder.push_back(temp);
    }
}
//重构二叉树
//参数分别是该子问题在后序遍历和中序遍历序列中的范围
node * rebuildBinaryTree(int postL, int postR, int inL, int inR)
{
    if(postL>postR)
    {
        return NULL;
    }
    node *root=new node;
    root->value=postorder[postR];
    int k=inL-1;
    while(inorder[++k]!=postorder[postR]);
    int numLeft=k-inL;
    //递归解决左子树的子问题
    root->left=rebuildBinaryTree(postL,postL+numLeft-1,inL,k-1);
    //递归解决右子树的子问题
    root->right=rebuildBinaryTree(postL+numLeft,postR-1,k+1,inR);
    return root;
}
// 层序遍历
void BFS(node *root)
{
    queue<node*>q;
    q.push(root);
    int i=0;
    while(q.size()!=0)
    {
        node* visit=q.front();
        q.pop();
        cout<<visit->value;
        ++i;
        if(i<N)
            cout<<" ";
        if(visit->left!=NULL)
            q.push(visit->left);
        if(visit->right!=NULL)
            q.push(visit->right);
    }
}

int main()
{
    handleInput();
    node *root=rebuildBinaryTree(0,N-1,0,N-1);
    BFS(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值