题目链接:
PREV-11 横向打印二叉树
思路:
首先递归建立二叉搜索树;
用字符串数组保存横向打印的二叉树,然后按层递归打印,注意打印的细节即可;
代码:
#include<bits/stdc++.h>
using namespace std;
string s[205];
const int maxn = 1e4 + 5;
int lf[maxn], rt[maxn], ln[maxn], rn[maxn];
inline void add(int x, int u) {
if(x < u) {
++ln[u];
if(lf[u] == 0) lf[u] = x;
else add(x, lf[u]);
}else {
++rn[u];
if(rt[u] == 0) rt[u] = x;
else add(x, rt[u]);
}
}
#define len(n) ((int)log10(n) + 1)
inline string itos(int n) {
string str = "";
while(n) str = (char)(n % 10 + '0') + str, n /= 10;
return str;
}
void dfs(int u, int pos) {
s[pos] += itos(u);
if(ln[u] || rn[u]) s[pos] += "-|";
string str = ".";
for(int i = len(u); i--;) str += ".";
int lp = pos + 1 + rn[lf[u]], rp = pos - 1 - ln[rt[u]];
for(int i = 1; i <= rn[u]; i++) {
s[pos - i] += str;
s[pos - i] += pos - i >= rp ? "|" : ".";
s[pos - i] += pos - i == rp ? "-" : ".";
}
for(int i = 1; i <= ln[u]; i++) {
s[pos + i] += str;
s[pos + i] += pos + i <= lp ? "|" : ".";
s[pos + i] += pos + i == lp ? "-" : ".";
}
if(lf[u]) dfs(lf[u], lp);
if(rt[u]) dfs(rt[u], rp);
}
int main() {
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
int v, root;
scanf("%d", &root);
while(~scanf("%d", &v)) add(v, root);
dfs(root, 100);
for(int i = 100 - rn[root]; i <= 100 + ln[root]; i++)
cout << s[i] << '\n';
return 0;
}