1127. ZigZagging on a Tree (30)
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 1Sample Output:
1 11 5 8 17 12 20 15
思路:由中序序列和后续序列构造一棵树我想不用多说了,用递归构造(后序遍历的最后一个节点是树根节点,确定这个根节点R,在中序遍历中,R的左边是它的左子树,右边是它的右子树,再递归)。然后这题的重点是“蛇形风骚遍历”,我是这样想的,规定一个vector v,定义int last指向本层的最后一个节点,首先将root节点放进vector,读完root后,令last = v.size();(此时是1,也就是第二层的第一个节点位置),然后将root节点的左右孩子放入v(如果不为NULL的话),下一层应该是从last到v.size()这些节点,定义一个flag,每读完一层让flag++,利用flag的奇偶性决定应该从last读到v.size()还是从v.size()读到last。这一层读完之后,再另last = v.size()也就是下一层的开始,同时把本层的各个节点的孩子节点放入v中...以此类推,知道v.size() = n为止。代码:
#include<bits/stdc++.h>
#define MAX 31
using namespace std;
class Node{
public:
int data;
Node *l = NULL;
Node *r = NULL;
};
int n;
int inOrder[MAX];
int postOrder[MAX];
void zigzaggingOrder(Node* root){
vector<Node*> v;
v.push_back(root);
int flag = 0;
int last = 0;
while(true){
if(v.size() == 1)
cout<<v[0]->data;
else{
if(flag % 2 == 1)
for(int i = v.size() - 1; i >= last; i--)
cout<<" "<<v[i]->data;
else
for(int i = last; i < v.size(); i++)
cout<<" "<<v[i]->data;
flag++;
}
if(v.size() == n)break;
int temp = v.size();
for(int i = last; i < temp; i++){
if(v[i]->l != NULL) v.push_back(v[i]->l);
if(v[i]->r != NULL) v.push_back(v[i]->r);
}
last = temp;
}
cout<<endl;
}
//由中序序列和后续序列构造一棵树
Node* create(int ib,int ie,int pb,int pe){
if(ib > ie)
return NULL;
Node* node = new Node();
node -> data = postOrder[pe];
int ibt = ib;
while(inOrder[ibt] != postOrder[pe]) ibt++;
node -> l = create(ib,ibt - 1,pb,pb + ibt - ib - 1);
node -> r = create(ibt + 1,ie,pb + ibt - ib,pe - 1);
return node;
}
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 = create(0,n - 1,0 ,n - 1);
zigzaggingOrder(root);
}