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 (≤), 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
建树,然后层序遍历就是 #include<iostream> #include<vector> #include<queue> using namespace std; vector<int> post,in,ans; int n;//总的节点数 struct node { int key; node* left; node* right; }; node* buildtree(node* root,int inleft,int inright,int postleft,int postright) { if(inleft>inright)//左边界大于右边界则返回空 return NULL; int i = inleft;//i从中序遍历的左边界开始 while(in[i]!=post[postright])//寻找根节点在中序遍历的下标 i++; //跳出while循环时,i是中序遍历的根节点下标 if(root==NULL) { root = new node(); root->key = in[i]; root->left = NULL; root->right = NULL; } root->left = buildtree(root->left,inleft,i-1,postleft,postleft+(i-inleft-1));//递归构造左子树 (i-inleft-1)表示中序遍历左子树的的元素一共多少个, -1表示减去根节点 root->right = buildtree(root->right,i+1,inright,postleft+(i-inleft),postright-1); return root; } void level(node* root) { queue<node*> q; q.push(root); while(!q.empty()) { node* temp = q.front();//temp指向队头元素 q.pop();//出队 ans.push_back(temp->key);//层序遍历的结果放在ans中 if(temp->left!=NULL)//左子树入队 q.push(temp->left); if(temp->right!=NULL)//右子树入队 q.push(temp->right); } } int main() { cin>>n; post.resize(n); in.resize(n); for(int i=0;i<n;i++) cin>>post[i]; for(int i=0;i<n;i++) cin>>in[i]; node* tree = NULL; tree = buildtree(tree,0,n-1,0,n-1); level(tree); for(int i=0;i<ans.size();i++) { cout<<ans[i]; if(i!=ans.size()-1) cout<<" "; } return 0; }