1020. Tree Traversals (25)

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<cstdio>
#include<queue>
using namespace std;
struct Node{
    int data;
    Node* lchild;
    Node* rchild;
}node;

int in[35],post[35],level[35];
int n;

Node* create(int postL,int postR,int inL,int inR){
    if(postL > postR){
        return NULL;
    }
    Node* root = new Node;
    root -> data = post[postR];
    int k;
    for(k = inL; k <= inR; k++){
        if(in[k] == post[postR]) break;
    }
    int numLeft = k - inL; //左子树的个数
    root->lchild = create(postL,postL+numLeft-1,inL,k-1); //左子树个数 
    root->rchild = create(postL+numLeft,postR-1,k+1,inR); //右子数个数 
    return root; 
}
int num = 0;
void BFS(Node* root){
    queue<Node*> q;
    q.push(root);
    while(!q.empty()){
        Node* now = q.front();
        q.pop();
        printf("%d",now->data);
        num++;
        if(num < n) printf(" ");
        if(now->lchild != NULL) q.push(now->lchild); //now节点后继 
        if(now->rchild != NULL) q.push(now->rchild); //2018.8.8 错误1
    }
}
int main(){
    scanf("%d",&n);
    for(int i = 0; i < n; i++){
        scanf("%d",&post[i]);
    }
    for(int i = 0; i < n; i++){
        scanf("%d",&in[i]);
    }
    Node* root = create(0,n-1,0,n-1); 
    BFS(root);
    return 0;
}
复制代码

 

posted @   王清河  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示