zoukankan      html  css  js  c++  java
  • [树的遍历]树的遍历(PTA)

    给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

    输入格式:

    输入第一行给出一个正整数N(≤),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

    输出格式:

    在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

    输入样例:

    7
    2 3 1 5 7 6 4
    1 2 3 4 5 6 7
    

    输出样例:

    4 1 6 3 5 7 2

    思路:

    已知:后序遍历和中序遍历
    画树的方法:
    第一步:根据后序遍历的特点,我们知道后序遍历最后一个节点即为根节点,即根节点4

    代码如下:

     1 #include <iostream>
     2 #include <bits/stdc++.h>
     3 using namespace std;
     4 const int maxn = 35;
     5 int hx[maxn],zx[maxn];
     6 int n;
     7 struct node
     8 {
     9     int l,r;
    10 };
    11 node pp[maxn];
    12 int build(int la,int ra,int lb,int rb)
    13 {
    14     if(lb>rb)
    15         return 0;
    16     int root,pos1,pos2;
    17     root=hx[ra];
    18     pos1=lb;
    19     while(zx[pos1]!=root)
    20         pos1++;
    21     pos2=pos1-lb;
    22     pp[root].l=build(la,la+pos2-1,lb,pos1-1);
    23     pp[root].r=build(la+pos2,ra-1,pos1+1,rb);
    24     return root;
    25 }
    26 void bfs()
    27 {
    28     queue<int> q;
    29     q.push(hx[n]);
    30     printf("%d",hx[n]);
    31     while(!q.empty())
    32     {
    33         int now=q.front();
    34         q.pop();
    35         if(now!=hx[n])
    36             printf(" %d",now);
    37         if(pp[now].l)
    38             q.push(pp[now].l);
    39         if(pp[now].r)
    40             q.push(pp[now].r);
    41     }
    42     printf("
    ");
    43 }
    44 int main()
    45 {
    46     scanf("%d",&n);
    47     for(register int i=1;i<=n;i++)
    48         scanf("%d",&hx[i]);
    49     for(register int i=1;i<=n;i++)
    50         scanf("%d",&zx[i]);
    51     build(1,n,1,n);
    52     bfs();
    53     //cout << "Hello world!" << endl;
    54     return 0;
    55 }
    View Code
     
     
  • 相关阅读:
    Python 设置 IP 代理 访问网页 ( 用户名密码验证代理 )
    Squid 3.3 部署 HTTP代理服务器
    文件打开模式 w+ r+ a+ 区别和辨析
    Python 学习工具书
    Conference Related to social network.
    Linux 使用故障小记
    正则表达式学习连接
    再次被windows操作系统伤害之吐槽
    数据结构——线性表的顺序表示(1)
    斐波那契数列两种算法的时间复杂度
  • 原文地址:https://www.cnblogs.com/SoulSecret/p/10579676.html
Copyright © 2011-2022 走看看