10562 - Undraw the Trees

本文介绍了一种使用递归方法处理树状结构数据的算法实现,通过遍历节点来构建并输出树形结构,适用于多种编程场景,如解析文件目录结构、XML或JSON等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

递归处理,不需要建树,每次判断当前所输出的节点是否是叶子节点,如果不是叶子节点,那么就继续处理该节点的子节点,具体细节见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
using namespace std;

void Print(vector<string>& data,int index,int pos){
	cout << data[index][pos]<<"(";
	if (index + 1 < data.size()){
		if (data[index + 1][pos] == '|'){
			int i = pos;
			while (i - 1 >= 0 && data[index + 2][i-1] == '-') i--;
			while (i<data[index+2].size()&&i<data[index+3].size()&&data[index + 2][i] == '-'){
				if (data[index+3][i]!=' '){
					Print(data,index+3,i);
				}
				i++;
			}
		}
	}
	cout << ")";
}

int main(){
	int T;
	cin >> T;
	string t;
	getline(cin,t);
	while (T--){
		vector<string> data;
		while (getline(cin, t)){
			if (t == "#") break;
			data.push_back(t);
		}
		cout << "(";
		if (data.size()){
			for (int i = 0; i < data[0].size(); i++){
				if (data[0][i] != ' '){
					Print(data, 0, i);
					break;
				}
			}
		}
		cout << ")" << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值