给后序序列和前序序列,要求求出这个二叉树的层序遍历
关键在于根据后序序列和前序序列定出二叉树。
root
,通过后序序列我们可以快速得知当前的root
(后序序列最后一个) 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