1. 程式人生 > >7-1 玩轉二叉樹

7-1 玩轉二叉樹

ret zhong code col push first spa 前序遍歷 else

給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹做個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將所有非葉結點的左右孩子對換。這裏假設鍵值都是互不相等的正整數。

先是建樹 快速套用模板

然後 他是按照層遍歷 那就用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; }

7-1 玩轉二叉樹