PAT 1130——

题目

原理剖析
代码
#include<bits/stdc++.h>
#pragma warning(disable:4996)
#pragma warning(disable:4703)
#pragma warning(disable:4700)
using namespace std;

typedef struct Tree {
	string key;
	int lchild;
	int rchild;
}BiTree;
string PrintTree(BiTree* T, vector<BiTree*> a) {
	if (T->lchild != -1 && T->rchild != -1) {
		return "("+ PrintTree(a[T->lchild],a)+ T->key + PrintTree(a[T->rchild], a) + ")";
	}
	if (T->lchild == -1 && T->rchild != -1) {
		return "(" + T->key + PrintTree(a[T->rchild], a) + ")";
	}
	if (T->lchild != -1 && T->rchild == -1) {
		return "(" + T->key + PrintTree(a[T->lchild], a) + ")";
	}
	if (T->lchild == -1 && T->rchild == -1) {
		return  T->key ;
	}
}

int main() {
	int number;
	cin >> number;
	vector<BiTree*> a(1);//先垫掉0空间
	int b[25];//map数组
	for (int i = 0; i != number; i++) {
		BiTree* node = new BiTree;
		cin >> node->key >> node->lchild >> node->rchild;
		a.push_back(node);
		if (node->lchild != -1) {
			b[node->lchild] = 1;
		}
		if (node->rchild != -1) {
			b[node->rchild] = 1;
		}
	}
	BiTree* root;//必须在for外部定义
	for (int i = 1; i <= number; i++) {//vector是从0开始的
		if (b[i] != 1) {
			root = a[i];//由于i的作用域仅在for内,因此要在循环内定义
			break;
		}
	}
	string ans = PrintTree(root, a);//根节点是肯定要的,其次存放结点的vector肯定也要
	if(ans[0]=='(')//测试点2就需要这句,原因是在边界只有1个字符时,是没有()
		ans=ans.substr(1, ans.size() - 2);
	cout << ans;
	return 0;
}

输出的一种等价写法

if (a.size() == 2) {//测试点2就需要这句,原因是在边界只有1个字符时,是没有()
		cout << root->key;
	}
	else{
		cout << ans.substr(1, ans.size() - 2);//默认从0开始,size包含了结尾的\0,因此截断掉首位为1——size-2
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值