PAT Left-View of Binary Tree (25 分) (2020秋)

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;

}

在这里插入图片描述


喵~
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值