zoukankan      html  css  js  c++  java
  • PAT Advance 1020

    题目:

    1020. Tree Traversals (25)

    时间限制
    400 ms
    内存限制
    32000 kB
    代码长度限制
    16000 B
    判题程序
    Standard
    作者
    CHEN, Yue

    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>
    #include<queue>
    using namespace std;

    typedef struct _Node
    {
    int num;
    struct _Node *lchild;
    struct _Node *rchild;
    }Node, *PNode;

    int t1[1001],t2[1001];
    int n;

    int getPosition(int a){
    int i;
    for(i=1;i<=n;i++)
    if(a == t2[i])
    return i;
    }

    void createTree(PNode &node, int i, int j, int len){
    if(len<=0){
    return ;
    }
    node = new Node;
    node->num = t1[i];
    node->lchild = NULL;
    node->rchild = NULL;
    int m = getPosition(t1[i]);
    createTree(node->lchild,i-len+m-j,j,m-j);//m-j:左子树len,len-1-(m-j):右子树len
    createTree(node->rchild,i-1,m+1,len-1-m+j);
    }

    void PreTravelTree(PNode pn) //前序递归遍历
    {
    if(pn){
    cout<<pn->num<<" "<<endl;
    PreTravelTree(pn->lchild);
    PreTravelTree(pn->rchild);
    }

    }

    int main()
    {
    int i;
    int r[100];
    queue<PNode> q;
    cin>>n;
    for(i=1;i<=n;i++)
    cin>>t1[i];
    for(i=1;i<=n;i++)
    cin>>t2[i];
    PNode root = NULL,temp;
    createTree(root,n,1,n);
    q.push(root);
    i=0;
    while(!q.empty()){
    temp = q.front();
    q.pop();
    r[i] = temp->num;
    i++;
    if(temp->lchild!=NULL)
    q.push(temp->lchild);
    if(temp->rchild!=NULL)
    q.push(temp->rchild);
    }
    cout<<r[0];
    for(i=1;i<n;i++)
    cout<<" "<<r[i];
    cout<<endl;
    return 0;
    }

  • 相关阅读:
    terminal下历史命令自动完成功能history auto complete
    Shell中while循环的done 后接一个重定向<
    python 链接hive
    shell 学习基地
    c++ 获取本地ip地址
    c++ 如何实现,readonly
    c++ 语法
    c++ 信号量
    vim插件介绍
    c++ memset 函数 及 坑
  • 原文地址:https://www.cnblogs.com/zjuzcj/p/3574631.html
Copyright © 2011-2022 走看看