zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    基于xmpp openfire smack开发之Android客户端开发[3]
    简单工厂,抽象工厂,工厂模式三者的对照
    【独具慧眼 推荐有礼】找出您心中的技术大牛 活动開始啦!
    ZOJ 3201
    具体解释站点沙盒期的原因表现与解决的方法
    工作,究竟意味着什么
    MVC之查询demo
    学习开淘宝网店
    快排的两种写法
    QTableWidget具体解释(样式、右键菜单、表头塌陷、多选等) (非代理)
  • 原文地址:https://www.cnblogs.com/xxxsans/p/12669818.html
Copyright © 2011-2022 走看看