Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in "zigzagging order" -- that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.
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 inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the zigzagging sequence of the tree in a line. 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:
8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1
Sample Output:
1 11 5 8 17 12 20 15
解题思路:首先中序遍历和后序遍历建树,再按层遍历存入res中,然后奇数层从右向左输出,偶数层从左向右输出即可
层序遍历使用队列进行判断,将该层的存入该深度的res中即可,并且将下一层的节点存入新的队列当中,最后将新的队列从新覆盖到旧的队列当中,结束的时候res中存的就是每一层的结果,注意奇数层从右向左输出,偶数层从左向右输出即可
这道题思路上很简单,考的其实就是建树和层序遍历
以下是代码
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 40;
struct Node
{
int val;
Node*right = NULL;
Node*left = NULL;
};
int inorder[N] , postorder[N];
int n;
Node *build(int il , int ir , int pl , int pr)
{
if(il > ir) return NULL;
Node *root = new Node;
root -> val = postorder[pr];
int k = il;
while(k <= ir && inorder[k] != root -> val) k++;
root -> left = build(il , k - 1 , pl , pl + k - 1 - il);
root -> right = build(k + 1 , ir , pr - ir + k , pr - 1);
return root;
}
void bfs(Node *r)
{
queue<Node*>q;
vector<int>res[N];
int depth = 1;
//奇数层从右向左
//偶数层从左向右
//根深度为1
q.push(r);
while(!q.empty())
{
int cnt = q.size();
queue<Node*>q1;
for(int i = 0;i < cnt;i ++)
{
Node *t = q.front();
if(t -> left) q1.push(t -> left);
if(t -> right) q1.push(t -> right);
q.pop();
res[depth].push_back(t -> val);
}
depth++;
q = q1;
}
for(int i = 1;i <= depth;i++)
{
if(i % 2)
{
if(i == 1) cout<<res[i][0];
else for(int j = res[i].size() - 1;j >= 0;j --) cout<<" "<<res[i][j];
}
else for(int j = 0;j < res[i].size();j ++) cout<<" "<<res[i][j];
}
}
int main()
{
cin>>n;
for(int i = 0;i < n;i ++) cin>>inorder[i];
for(int i = 0;i < n;i ++) cin>>postorder[i];
Node *root = build(0 , n - 1 , 0 , n - 1);
bfs(root);
return 0;
}