PAT1020: Tree Traversals

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

思路
1.由后序遍历序列的最后一位确定树的根节点,根据根节点在中序遍历序列的位置确定左右子树,然后按照这个规律不停地分割两个序列就行,
2.分割以前序遍历的形式进行,用一个二维vector levels存储遍历到的节点levels[level][i]和其对应层级level,最后输出levels不为空的部分就是层次遍历。
3.输出需要注意最后一个节点输出后面不能有空格
代码
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int>> levels(31);
vector<int> postorder(31);
vector<int> inorder(31);
int index;

void findroot(int pfirst,int plast,int ifirst,int ilast,int level)
{
    if(ifirst > ilast || pfirst > plast)
        return;
    int i = 0;
    while(postorder[plast] != inorder[i+ifirst]) i++;
    levels[level].push_back(postorder[plast]);
    findroot(pfirst,pfirst + i - 1,ifirst,ifirst + i - 1,level + 1);
    findroot(pfirst + i,plast - 1,ifirst + i + 1,ilast,level + 1);
}

int main()
{
   int N;
   while(cin >> N)
   {
       for(int i = 1;i <= N;i++)
       {
           cin >> postorder[i];
       }
       for(int i = 1;i <= N;i++)
       {
           cin >> inorder[i];
       }
       index = 0;

       //preorder and store every level's node
       findroot(1,N,1,N,1);

       //print
       int lastout = 0; //to ensure the last output has no space in the end
       for(int i = 1;i <= N;i++)
       {
           if(levels[i].empty())
            continue;
           for(int j = 0;j < levels[i].size();j++)
           {
            if(lastout == N - 1)
                cout << levels[i][j];
            else
            {
                cout << levels[i][j]<<" ";
                ++lastout;
            }
           }
       }
       cout << endl;
   }
}


 
原文地址:https://www.cnblogs.com/0kk470/p/7623718.html