输入数据,不知道一个父亲节点具体有几个儿子节点时,可以考虑用此方法建树。
每两个“ . ”代表一层。
1
..2
....3
....4
......5
....6
......7
........8
..9
....10
..11
....12
#include <iostream>
#include <cstdio>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#define Int int
using namespace std;
int a[25];
int p[25];
vector<int> child[25];
int root = 0;
void build_tree(int cur, int level, int father) {
if(cur == 13)
return ;
if(a[cur] == level * 2) {
p[cur] = father;
build_tree(cur+1, level+1, cur);
}
else
build_tree(cur, level-1, p[father]);
}
void print_tree(int node, int level) {
for(int j = 1; j <= 2*level; j++) printf(" ");
printf("%d\n", node);
for(int i = 0; i < child[node].size(); i++)
print_tree(child[node][i], level+1);
//if(!child[node].size()) printf("\n");
}
int main()
{
freopen("ztest.txt","r",stdin);
memset(a, 0, sizeof(a));
memset(p, 0, sizeof(p));
for(int i = 0; i < 25; i++)
child[i].clear();
string str;
for(int i = 1; i <= 12; i++) {
getline(cin, str);
//cout << str << endl;
for(int j = 0 ;j < str.size(); j++)
if(str[j] == '.')
a[i]++;
}
build_tree(1, 0, 0);
for(int i = 1; i <= 12; i++) {
printf("%d ", p[i]);
child[p[i]].push_back(i);
}
print_tree(root, 0);
}