1020. Tree Traversals (25)
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 7Sample Output:
代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
int elem;
};
TreeNode* BinaryTreeFromOrderings(int* inorder, int* aftorder, int length)
{
if(length == 0)
{
return NULL;
}
TreeNode* node = new TreeNode;//Noice that [new] should be written out.
node->elem = *(aftorder+length-1);
int rootIndex = 0;
for(;rootIndex < length; rootIndex++)//a variation of the loop
{
if(inorder[rootIndex] == *(aftorder+length-1))
break;
}
node->left = BinaryTreeFromOrderings(inorder, aftorder , rootIndex);
node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, aftorder + rootIndex , length - (rootIndex + 1));
return node;
}
void PrintNodeByLevel(TreeNode*pRoot)
{
if(pRoot==NULL)
return;
vector<TreeNode*>vec;
//运用了vector可以利用其动态增长的特性
//但是这个时候标号就不能用迭代器了,因为增长的时候迭代器会失效
vec.push_back(pRoot);
int intcur=0;//指向当前节点
int intlast=1,cur=0,last,flag=0;
while(cur<vec.size())
{
last=vec.size();//指向本层节点的后一个节点
if(vec[cur]->elem!=0&&flag==1)
{
printf(" %d",vec[cur]->elem);
}
if(vec[cur]->elem!=0&&flag==0)
{
flag=1;
printf("%d",vec[cur]->elem);
}
if(vec[cur]->left!=NULL)
vec.push_back(vec[cur]->left);
if(vec[cur]->right!=NULL)
vec.push_back(vec[cur]->right);
cur++;
}
//每一次循环都将下一层的节点压入vector,并且打印完本层节点
}
int main(int argc, char** argv)
{
int n;
while(scanf("%d",&n)==1)
{
int *af=new int[n+1];
int *in=new int[n+1];
for(int i=0;i<n;i++)
{
scanf("%d",&af[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d",&in[i]);
}
PrintNodeByLevel(BinaryTreeFromOrderings(in, af, n));
printf("\n");
}
return 0;
}