资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
二叉树可以用于排序。其原理很简单:对于一个排序二叉树添加新节点时,先与根节点比较,若小则交给左子树继续处理,否则交给右子树。
当遇到空子树时,则把该节点放入那个位置。
比如,10 8 5 7 12 4 的输入顺序,应该建成二叉树如下图所示,其中.表示空白。
…|-12
10-|
…|-8-|
…|…|-7
…|-5-|
…|-4
本题目要求:根据已知的数字,建立排序二叉树,并在标准输出中横向打印该二叉树。
输入格式
输入数据为一行空格分开的N个整数。 N<100,每个数字不超过10000。
输入数据中没有重复的数字。
输出格式
输出该排序二叉树的横向表示。为了便于评卷程序比对空格的数目,请把空格用句点代替:
样例输入1
10 5 20
样例输出1
…|-20
10-|
…|-5
样例输入2
5 10 20 8 4 7
样例输出2
…|-20
…|-10-|
…|…|-8-|
…|…|-7
5-|
…|-4
测试用例1:1 3 5 7 9 2 4 6 8
测试用例2:50 10 40 20 15 22 3
测试用例3:100 25 75 200 14 22 19 28 17 21 33 35 29
测试用例4:40 68 129 15 23 21 9 16 22 27 98 144 215 7 13 19 26
#include <bits/stdc++.h>
using namespace std;
struct node{
int val;
node* left;
node* right;
node(){
left = NULL;
right = NULL;
}
};
node* res;
string str[105];
int t = 0;
//初始化树
void init(node* &res,int x){
if(res == NULL){
res = new node;
res->val = x;
return ;
}
if(x < res->val) init(res->left,x);
else init(res->right,x);
}
//数字的长度
int num(int n){
stringstream temp;
temp<<n;
string a;
temp>>a;
return a.length();
}
//遍历树,idx = 1时为根节点,x存储需要输出的.的长度
void post(node* res,int idx,int x){
if(res->right == NULL && res->left == NULL){
for(int i = 0;i < x-1;i++) str[t]+=".";
str[t]+="|-";
stringstream s;
s<<res->val;
string ss;
s>>ss;
str[t]+=ss;
t++;
return ;
}
if(res->right != NULL) {
if(idx == 1) post(res->right,idx+1,x+num(res->val)+2);
else post(res->right,idx+1,x+num(res->val)+3);
}
if(idx == 1) {
stringstream s;
s<<res->val;
string ss;
s>>ss;
str[t]+=ss;
str[t]+="-|";
t++;
}
else{
for(int i = 0;i < x-1;i++) str[t]+=".";
str[t]+="|-";
stringstream s;
s<<res->val;
string ss;
s>>ss;
str[t]+=ss;
str[t]+="-|";
t++;
}
if(res->left != NULL){
if(idx == 1) post(res->left,idx+1,x+num(res->val)+2);
else post(res->left,idx+1,x+num(res->val)+3);
}
return ;
}
int main(){
int x;
while(scanf(" %d",&x) == 1){
init(res,x);
}
post(res,1,0);
string s = "-|";
//填充|符号
for(int i = 0;i < t;i++){
if(str[i].length() != 0){
for(int j = 0;j < str[i].length();j++){
if(str[i].substr(j,2) == s){
int k = i - 1;
while(k >= 0 && str[k][j+1] != '|'){
if(str[k].length() < j+1) break;
if(str[k][j+1] == '.')str[k][j+1] = '|';
k--;
}
k = i+1;
while(str[k][j+1] != '|' && k <= t-1){
if(str[k].length() < j+1) break;
if(str[k][j+1] == '.') str[k][j+1] = '|';
k++;
}
}
}
}
}
for(int i = 0;i < t;i++){
if(str[i].length() != 0){
cout<<str[i]<<endl;
}
}
return 0;
}