PAT Left-View of Binary Tree (25 分) (2020秋)
输入样例
8
2 3 1 5 4 7 8 6
1 2 3 6 7 4 5 8
输出样例
1 2 3 4 5
输出每层第一个结点即可
基本操作
#include<bits/stdc++.h>
using namespace std;
const int N=30;
struct node
{
int data,high;
struct node *left,*right;
};
int in[N],pre[N];
node*build(int pl,int pr,int inl,int inr)
{//根据前序和中序建树
if(pl>pr)return NULL;
node *root=new node;
root->data=pre[pl];
//当前前序序列第一个结点就是根节点的值
int k;
for(k=inl;k<=inr;k++)
//遍历中序遍历,找到中序遍历中对应的点
{
if(root->data==in[k]) break;
}
int leftNodeNum=k-inl;//左子树的个数
root->left=build(pl+1,pl+leftNodeNum,inl,k-1);
root->right=build(pl+leftNodeNum+1,pr,k+1,inr);
return root;
}
int maxhigh=-1,vist[N]={0};
//maxhigh暴力树的最大高度
//vist存放最后的结果
void bfs(node *root)
{
//层序遍历
queue<node*>q;
q.push(root);//加入当前结点
root->high=1;//设置结点高度
while(q.size())
{
node *now=q.front();
if(now->high>maxhigh) maxhigh=now->high;//遍历看看最后一层的高度
if(!vist[now->high]) //如果当前高度没有被访问,更新
vist[now->high]=now->data;
q.pop();
if(now->left!=NULL)
//左子树不为空,加入左子树,记得更新高度
{
now->left->high=now->high+1;
q.push(now->left);
}
if(now->right!=NULL)
//右子树不为空,加入右子树,记得更新高度
{
now->right->high=now->high+1;
q.push(now->right);
}
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
{
freopen("12.txt","r",stdin);
}
#endif
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>in[i];
for(int i=0;i<n;i++) cin>>pre[i];
node* root=build(0,n-1,0,n-1);
bfs(root);
for(int i=1;i<=maxhigh;i++)
{//遍历vist数组,输出结果
cout<<vist[i];
if(i<maxhigh) cout<<" ";
}
return 0;
}
喵~