ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

PAT Advanced 1020 Tree Traversals(25)

2022-08-19 00:02:54  阅读:153  来源: 互联网

标签:node 25 PAT 1020 index int t1 ++ line


题目描述:

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

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

Sample Output:

4 1 6 3 5 7 2

算法描述:二叉树的遍历

题目大意:

给出一棵二叉树的 后序遍历 和 中序遍历,输出层序遍历

#include<iostream>
using namespace std;

int n, po[40], in[40]; //po 后序  in 中序
struct node
{
    int val;
    node*left, *right;
};
node* makenode(int h1, int t1, int h2, int t2) //两序列的首尾
{
    if(h1 > t1)    return NULL;
    node* p = new node;
    p->val = po[t1]; //后序尾元素即为根
    int index;
    for(index = h2 ; in[index] != po[t1] ; index ++); //index 即根在中序中的下标
    p->left = makenode(h1, index - 1 - h2 + h1, h2, index - 1); //两序列中子树长度相等  所以可以分别推出左子树的t1和右子树的h1
    p->right = makenode(index - h2 + h1, t1 - 1, index + 1, t2);
    return p;
}

int main()
{
    cin >> n;
    for(int i = 0 ; i < n ; i ++)   cin >> po[i];
    for(int i = 0 ; i < n ; i ++)   cin >> in[i];
    
    node* root = makenode(0, n - 1, 0, n - 1);
    node* q[40];
    int head = 0, tail = 0;
    q[tail ++] = root;
    while(head < tail)
    {
        if(head != 0)   cout << ' ';
        node* p = q[head ++]; // 出队
        cout << p->val;
        if(p->left)   q[tail ++] = p->left; // 入队
        if(p->right)  q[tail ++] = p->right;
    }
    return 0;
}

标签:node,25,PAT,1020,index,int,t1,++,line
来源: https://www.cnblogs.com/yztozju/p/16600570.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有