1577:Falling Leaves【2019北大夏令营G】
-
总时间限制:
1000ms
-
内存限制:
65536kB
-
描述
A tree like the one in Figure 1 is also a binary search tree of letters. A binary search tree of letters is a binary tree of letters in which each node satisfies: The root’s data comes later in the alphabet than all the data in the nodes in the left subtree. The root’s data comes earlier in the alphabet than all the data in the nodes in the right subtree.
The problem: Consider the following sequence of operations on a binary search tree of letters: Remove the leaves and list the data; removed; Repeat this procedure until the tree is empty
Starting from the tree below on the left, we produce the sequence of trees shown, and then the empty tree
by removing the leaves with data
BDHPY
CM
GQ
K
Your problem is to start with such a sequence of lines of leaves from a binary search tree of letters and output the preorder traversal of the tree.
-
输入
The input will contain one or more data sets. Each data set is a sequence of one or more lines of capital letters. The lines contain the leaves removed from a binary search tree in the stages described above. The letters on a line will be listed in increasing alphabetical order.
Data sets are separated by a line containing only an asterisk (‘*’). The last data set is followed by a line containing only a dollar sign (‘$’). There are no blanks or empty lines in the input.
-
输出
For each input data set, there is a unique binary search tree that would produce the sequence of leaves. The output is a line containing only the preorder traversal of that tree, with no blanks.
-
样例输入
BDHPY CM GQ K * AC B $
-
样例输出
KGCBDHQMPY BAC
题解
- 从根开始构造二叉搜索树,然后前序print
#include <iostream>
#include <deque>
using namespace std;
struct Node
{
char c;
Node*left,*right;
Node():c(0),left(0),right(0){}
};
void pre_order(Node*r)
{
if(r==0){
return;
}
cout<<r->c;
pre_order(r->left);
pre_order(r->right);
}
int main()
{
string line="*";
bool is_first=1;
while(line[0]!='$' && cin>>line){
if(is_first==0) cout<<endl;
is_first=0;
deque<string>leaves={line};
int node_num=line.size();
while(cin>>line && line[0]!='$' && line[0]!='*'){
leaves.push_front(line);
node_num+=line.size();
}
if(node_num){
//construct
Node*root=new Node[node_num];
root->c=leaves[0][0];
int next_node_id=1;
int e=leaves.size();
for(int i=1; i<e; ++i){
string leaf=leaves[i];
for(char c:leaf){
Node*pre=root;
//insert c
while(1){
if(c<pre->c){
if(pre->left){
pre=pre->left;
}
else{
pre->left=root+next_node_id;
root[next_node_id].c=c;
++next_node_id;
break;
}
}
else if(c>pre->c){
if(pre->right){
pre=pre->right;
}
else{
pre->right=root+next_node_id;
root[next_node_id].c=c;
++next_node_id;
break;
}
}
}
}
}
//print
pre_order(root);
}
}
return 0;
}