横向打印二叉树

来源:互联网 发布:ios多线程编程 面试 编辑:程序博客网 时间:2024/06/05 07:39
问题描述

二叉树可以用于排序。其原理很简单:对于一个排序二叉树添加新节点时,先与根节点比较,若小则交给左子树继续处理,否则交给右子树。

当遇到空子树时,则把该节点放入那个位置。

比如,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
#include <iostream>#include <cstdio>#include <cstring>#include <sstream>#include <utility>#include <string>#include <queue>using namespace std;const int maxn = 105 * 4;const int INF = 0x3f3f3f3f;struct Node {int id;string fmt;} nodes[maxn];int a[maxn], root, lineno[maxn], no, n;bool rootinit;string fmt[maxn];//打印形式void insertTree(int rt, int val){    if(a[rt] == INF) {        a[rt] = val;        return;    }    if(val > a[rt]) insertTree(rt << 1 | 1, val);    else            insertTree(rt << 1, val);}void setLineNo(int rt){    if(a[rt << 1 | 1] != INF)   setLineNo(rt << 1 | 1);    lineno[rt] = no++;    //printf("%d line:%d id:%d\n", a[rt], lineno[rt], rt);    if(a[rt << 1] != INF)   setLineNo(rt << 1);}bool inline between(int x, int y, int z){return (z - x) * (z - y) < 0;}char itoa(int x){return x + '0';}string atostr(int x){string res = "";while(x) {res = itoa(x % 10) + res;x /= 10;}return res;}void setFormat(int rt){queue<int> q;q.push(rt);while(!q.empty()) {int x = q.front();q.pop();//cout << x << endl;if(x == 1) {fmt[x] = atostr(a[x]) + "-|";}else {fmt[x] = fmt[x/2];if(between(lineno[x/4], lineno[x/2], lineno[x])) {for(int i = 0; i < fmt[x].length()-1; i++) {if(fmt[x][i] == '-' || (fmt[x][i] >= '0' && fmt[x][i] <= '9'))fmt[x][i] = '.';}}else {for(int i = fmt[x].length()-2; i >= 0; i--) {if(fmt[x][i] == '|' && fmt[x][i+1] == '-') {fmt[x][i] = '.';break;}}for(int i = 0; i < fmt[x].length()-1; i++) {if(fmt[x][i] == '-' || (fmt[x][i] >= '0' && fmt[x][i] <= '9'))fmt[x][i] = '.';}}fmt[x] += "-" + atostr(a[x]);if(a[x << 1] != INF || a[x << 1 | 1] != INF)fmt[x] += "-|";}if(a[x << 1] != INF)q.push(x << 1);if(a[x << 1 | 1] != INF)q.push(x << 1 | 1);}}void printFormat(int rt){if(a[rt << 1 | 1] != INF)printFormat(rt << 1 | 1);cout << fmt[rt] << endl;if(a[rt << 1] != INF)printFormat(rt << 1);}int main(){    //freopen("in.txt", "r", stdin);    string line;    getline(cin, line);    stringstream ss(line);    int tmp;    fill(a, a + maxn, INF);    root = 1;no = 0;n = 0;    while(ss >> tmp) {insertTree(root, tmp);n++;    }    setLineNo(root);    setFormat(root);    printFormat(1);    return 0;}

原创粉丝点击