藍橋杯 歷屆試題 橫向打印二叉樹(C++ ac代碼,所有測試用例及結果圖)

資源限制
時間限制: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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章