Binary Tree Traversals HDU - 1710

版权声明:文章全是博主转载, 请随意操作。 https://blog.csdn.net/ggqinglfu/article/details/82119266

Binary Tree Traversals

 HDU - 1710 

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

这个前序中序输出后序的, 必须得上代码WTFWTMQAQ..... 

上次看见你因为你进化成了数字带空格的换行, 整的俺不要你了都

练习串串练多了。。。。。。。

二叉树便利遍历。。。。

虽然写的麻烦, 但ac了啦啦啦啦啦~~~

Status Accepted
Time 46ms
Memory 3028kB
Length 1067
Lang G++
Submitted 2018-08-27 15:27:43
Shared  
RemoteRunId 26093142
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
using  namespace std;
struct tree
{
    int data;
    struct tree *l, *r;
};
int a[1001], b[1001], n;
 struct tree *build(int *a, int n, int *b)
{
    if(n == 0) return NULL;
    int i;
    struct tree *root;
    root = new tree;
    root->data = a[0];
    for(i = 0; i < n; i++)
    {
        if(a[0] == b[i])
            break;
    }
    root->l = build(a + 1, i, b);
    root->r = build(a + 1 + i, n - i - 1, b + i +1);
    return root;
}

 void hou(struct tree *root)
 {

     if(root)
     {
         hou(root->l);
         hou(root->r);
         printf("%d",root->data);
         if(n)
            {
            printf(" ");
            n--;
            }
         else printf("\n");
     }
 }
int main()
{
   struct tree *root;
   while(~scanf("%d",&n))
   {
        for(int i = 0; i < n; i++)
            scanf("%d",&a[i]);
        for(int i = 0; i < n; i++)
            scanf("%d",&b[i]);
           root = build(a,n,b);
           n-=1;
           hou(root);
   }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ggqinglfu/article/details/82119266
今日推荐