浙江财经大学
信工学院ACM集训队

HDU 1710 Binary Tree Traversals(二叉树)

本文由 Ocrosoft 于 2016-05-11 11:18:10 发表

Binary Tree Traversals

Time Limit : 1000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 37   Accepted Submission(s) : 25

Font: Times New Roman | Verdana | Georgia

Font Size:  

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

Solution

给出一个二叉树的先序遍历和中序遍历,求后序遍历。代码注释比较详细。

#include <iostream>
#include <cstdio>
using namespace std;
int tree1[1001],tree2[1001];
//tree1的位置,tree2的位置,树的节点数,是否主根节点
void dfs(int a,int b,int n,int flag)
{
    if(n==1){cout<<tree1[a]<<" ";return;}//节点只有一个,是叶子节点,输出
    else if(n<=0)return;//没有节点,返回
    int i;
    for(i=0;tree1[a]!=tree2[b+i];i++);//找到tree2中与tree1[a]相等的数
    dfs(a+1,b,i,0);//搜索左子树
    //tree1[a+1]是左子树的根节点,tree2[b]也是右子树的根节点
    //i是左子树的节点个数
    dfs(a+i+1,b+i+1,n-i-1,0);//搜索右子树
    //tree2[a+i+1]是右子树的根节点,tree2[b+i+1]也是右子树的根节点
    //n-i-1是左子树的节点个数
    if(flag)cout<<tree1[a];//输出主根节点的时候不输出空格
    else cout<<tree1[a]<<" ";//输出其他根节点的时候后跟空格
}
int main()
{
    int n;
    while(cin>>n)
    {
        for(int i=0; i<n; i++)cin>>tree1[i];
        for(int i=0; i<n; i++)cin>>tree2[i];
        dfs(0,0,n,1);
        cout<<endl;
    }
    return 0;
}

欢迎转载,请保留出处与链接。Ocrosoft » HDU 1710 Binary Tree Traversals(二叉树)

点赞 (0)or拍砖 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址