标签:++ for using scanf main bsp int ace pac
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
先是建树 快速套用模板
然后 他是按照层遍历 那就用bfs 如果按照某种序遍历 用dfs
#include<bits/stdc++.h> using namespace std; int n; int zhong[35]; int qian[35]; int le[35],ri[35]; int built(int x1,int y1,int x2,int y2) { if(x2>y2||x1>y1)return 0; int root=qian[x1]; int p=x2; while(zhong[p]!=root)p++; int cnt=p-x2; ri[root]=built(x1+cnt+1,y1,x2+cnt+1,y2); le[root]=built(x1+1,x1+cnt,x2,x2+cnt-1); return root; } void bfs(int root) { queue<int >q; q.push(root); printf("%d",root); int first=1; while(!q.empty()) { int u=q.front();q.pop(); if(first)first=0; else printf(" %d",u); if(ri[u]!=0)q.push(ri[u]); if(le[u]!=0)q.push(le[u]); } } int main() { scanf("%d",&n); for(int i=1;i<=n;i++)scanf("%d",&zhong[i]); for(int i=1;i<=n;i++)scanf("%d",&qian[i]); int root=qian[1]; built(1,n,1,n); bfs(root); return 0; }
标签:++ for using scanf main bsp int ace pac
原文地址:https://www.cnblogs.com/bxd123/p/10391645.html