一种实用的建树方法

输入数据,不知道一个父亲节点具体有几个儿子节点时,可以考虑用此方法建树。

每两个“ . ”代表一层。

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);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值