zoukankan      html  css  js  c++  java
  • 7-1 玩转二叉树

    给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

    先是建树 快速套用模板

    然后  他是按照层遍历  那就用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;
    }
  • 相关阅读:
    分布式系统学习一-概念篇
    JAVA多线程学习九-原子性操作类的应用
    JAVA多线程学习八-多个线程之间共享数据的方式
    JAVA多线程学习七-线程池
    vue 工作随笔
    智能云课堂整理
    mysql
    模板引挚 jade ejs
    node实战小例子
    昭山欢node资料学习笔记
  • 原文地址:https://www.cnblogs.com/bxd123/p/10391645.html
Copyright © 2011-2022 走看看