• Binary Tree Traversals 二叉树遍历


    In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
    Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.

    Input

    The input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.

    Output

    For each test case print a single line specifying the corresponding postorder sequence.

    Sample Input

    9
    1 2 4 7 3 5 8 9 6
    4 7 2 1 8 5 9 3 6

    Sample Output

    7 4 2 8 9 5 6 3 1

    给出前序遍历和中序遍历,求后序遍历。

    #include<iostream>
    #include<algorithm>
    #include<cmath>
    #include<cstdio>
    typedef long long ll;
    using namespace std;
    const ll inf = 1e18;
    const int mod = 1000000007;
    const int mx = 1e6; //check the limits, dummy
    ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
    #define swa(a,b) a^=b^=a^=b
    #define re(i,a,b) for(ll i=(a),_=(b);i<_;i++)
    #define rb(i,a,b) for(ll i=(b),_=(a);i>=_;i--)
    #define clr(a) memset(a, 0, sizeof(a))
    #define lowbit(x) ((x)&(x-1))
    #define mkp make_pair
    int N;
    void ans(int* im1, int* im2, int a, int b, int N, int flag)
    {
    	if (N == 1)
    	{
    		printf("%d ", im1[a]);
    		return;
    	}
    	else if (N == 0) return;
    	int i = 0;
    	for (; im1[a] != im2[b + i]; i++);
    	ans(im1, im2, a + 1, b, i, 0);
    	ans(im1, im2, a + i + 1, b + i + 1, N - i - 1, 0);
    	if (flag) printf("%d\n", im1[a]);
    	else printf("%d ", im1[a]);
    }
    int main()
    {
    	while (cin>>N&&N)
    	{
    		int* im1 = (int*)malloc(sizeof(int) * (N + 2));
    		int* im2= (int*)malloc(sizeof(int) * (N + 2));
    		for (int i = 1; i <= N; i++) scanf("%d", &im1[i]);
    		for (int i = 1; i <= N; i++) scanf("%d", &im2[i]);
    		ans(im1, im2, 1, 1, N, 1);
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    node.js 基础篇
    node.js 开发环境搭建
    Velocity VelocityEngine 支持多种loader 乱码问题
    tomcat集群及session共享
    上海支付宝终面后等了两周,没能收到offer却来了杭州淘宝的电话面试
    支付宝hr终面,忐忑的等待结果
    mysql 数据范围总结
    rsync同步文件(多台机器同步代码...)
    linux基础命令
    路飞学城项目之前后端交互,跨域问题
  • 原文地址:https://www.cnblogs.com/xxxsans/p/12669818.html
Copyright © 2020-2023  润新知