首页 > 其他 > 详细

PAT(Advanced Level)A1020. Tree Traversals

时间:2020-09-29 13:12:24      阅读:35      评论:0      收藏:0      [点我收藏+]

题意

给后序序列和前序序列,要求求出这个二叉树的层序遍历

思路

  • 关键在于根据后序序列和前序序列定出二叉树。

    • 二叉树是递归定义的,所以根据后序序列和中序序列定树同样是递归式的
    • 1??每次都先在中序序列中找到根root,通过后序序列我们可以快速得知当前的root(后序序列最后一个)
    • 2??统计出右子树结点的个数(统计左子树的也可以)
    • 3??递归处理左子树,右子树
    • 递归的边界是看区间长度,左>右就退出
    			    1
    			   / 			  2   3
    			 / \ / 			4  5 6  7
    
    index:       0 1 2 3 4 5 6
    postorder:   4 5 2 6 7 3 1
    inoder:      4 2 5 1 6 3 7
    
  • 层序遍历:其实和普通的BFS没什么区别,主要是层序遍历,所以每次我们都是出一层长度的结点并进行扩充。没有什么难度

代码

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int post_order[50], in_order[50];
int N;
vector<int> ans;
struct Node
{
    int val;
    Node* lchild;
    Node* rchild;
};
Node* Create(int postL, int postR, int inL, int inR)
{
    if(postL > postR)
        return NULL;
    Node* root = new Node;
    root->val = post_order[postR];
    int pos;
    for(pos=inL;pos<=inR;pos++)
    {
        if(in_order[pos] == root->val)
            break;
    }
    int numRight = inR - pos;   //右子树的区间长度
    root->rchild = Create(postR - numRight, postR - 1, pos + 1, inR);
    root->lchild = Create(postL, postR - numRight - 1, inL, pos - 1);
    return root;
}
void Level_order(Node* root)
{
    queue<Node*> q;
    q.push(root);
    while(!q.empty())
    {
        int size = q.size();
        for(int i=0;i<size;i++)
        {
            auto cur = q.front();
            q.pop();
            ans.emplace_back(cur->val);
            if(cur->lchild)
            {
                q.push(cur->lchild);
            }
            if(cur->rchild)
            {
                q.push(cur->rchild);
            }
        }
    }
}
int main()
{
    cin >> N;
    for(int i=0;i<N;i++)
        cin >> post_order[i];
    for(int i=0;i<N;i++)
        cin >> in_order[i];
    Node* root = Create(0, N-1, 0, N-1);
    Level_order(root);
    for(int i=0;i<ans.size();i++)
        i == ans.size() - 1 ? cout << ans[i] : cout << ans[i] << " ";
    return 0;
}

PAT(Advanced Level)A1020. Tree Traversals

原文:https://www.cnblogs.com/MartinLwx/p/13748989.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!