1020 Tree Traversals (25 point(s))
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. 重建树,体会createTree()函数;
2. 采用队列的层次遍历。
注意点:
1. C++11引入nullptr作为空指针。C++11以下支持NULL(视为0)。尽量使用nullptr。
2. createTree函数注意终止条件(即某子树不存在,left>right,返回空指针)。
#include<iostream>
#include<queue>
using namespace std;
int post[30];
int in[30];
struct Node{
int data;
Node* left;
Node* right;
Node(int d):data(d),left(NULL),right(NULL){ }
};
Node* createTree(int root,int left,int right){
//根据post[]的root位置的元素和in[]的left到right区间的元素构建树
if(left>right) return NULL;
Node* r = new Node(post[root]);
int idx = left;
while(in[idx]!=post[root]){
idx++;
}//idx是在中序遍历中根节点的位置
r -> left = createTree(root-right+idx-1,left,idx-1);
r -> right = createTree(root-1,idx+1,right);
return r;//必须返回当前的根节点
}
void levelOrder(Node* root){
queue<Node*> q;
q.push(root);
bool isFirst=true;
while(!q.empty()){
Node* front = q.front();
q.pop();
if(isFirst){
cout<<front->data;
isFirst = false;
}
else cout<<" "<<front->data;
if(front->left!=NULL) q.push(front->left);
if(front->right!=NULL) q.push(front->right);
}
}
int main(void){
int n;cin>>n;
for(int i=0;i<n;i++) cin>>post[i];
for(int i=0;i<n;i++) cin>>in[i];
Node* root = createTree(n-1,0,n-1);
levelOrder(root);
return 0;
}