首页 > 代码库 > HDU 1710 Binary Tree Traversals

HDU 1710 Binary Tree Traversals

Problem Description
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.

In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.

In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.

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 <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <queue>
#include <algorithm>
#define mem(f) memset(f,0,sizeof(f))
#define M 100005
#define mod 1000000007
#define lson o<<1, l, m
#define rson o<<1|1, m+1, r
using namespace std;
typedef long long LL;
const int MAX = 0x3f3f3f3f;
const int maxn = 1005;

int n, k, pre[maxn], post[maxn], mid[maxn];

void build(int l1, int r1, int l2, int r2) {
    if(l1 > r1 || l2 > r2) return;
    int o = pre[l1], pos;

    for(int i = l2; ; i++) {
        if(mid[i] == o) {
            pos = i;
            break;
        }
    }
    int cntl = pos-l2, cntr = r2-pos; //printf("%d %d\n", cntl, cntr);
    build(l1+1, l1+cntl, l2, pos-1);
    build(l1+cntl+1, r1, pos+1, r2);
    post[k++] = o;
}

int main()
{
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; i++) scanf("%d", &pre[i]);
        for(int i = 1; i <= n; i++) scanf("%d", &mid[i]);
        k = 0;
        build(1, n, 1, n);
        for(int i = 0; i < k-1; i++) printf("%d ",post[i]);
        printf("%d\n", post[k-1]);
    }
    return 0;
}





HDU 1710 Binary Tree Traversals