pta :7-11 列出叶结点

 题目:

样例输入: 

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

样例输出:1 4 5

想法:记录每个节点的左右节点,在操作

tuple<int, int> das[100]; //储存节点为i的左节点,右节点
bool vis1[20];//判断某个节点是否有father,没有的那就是head节点
queue<int> que;
int main(int args, char** argv)
{
	/*ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cin.tie(nullptr);*/
	int n;
	cin >> n;
	ifor(i, 0, n - 1)
	{
		char c1, c2;
		cin >> c1 >> c2;
		if ( c1 ^ '-' )
		{
			get<0>(das[i]) = c1 - '0';
			vis1[c1 - '0'] = 1;
		}else
			get<0>(das[i]) = -1;
		if ( c2 ^ '-' )
		{
			get<1>(das[i]) = c2 - '0';
			vis1[c2 - '0'] = 1;
		}else
			get<1>(das[i]) = -1;
	}
	for ( int i = 0; i <= n - 1; i++ )
	{
		if ( !vis1[i] )
		{
			que.push(i); break;
		}
	}
	bool once = 1;
	int cnt = 0;
//     cout<<que.front()<<endl;

//层次遍历
	while ( !que.empty() )
	{
		int tou = que.front();
		que.pop();
        int cnt=0;
//技巧:对于一个根节点i,以及他的左节点、右节点的二叉树而言,cnt=0,就代表她是叶节点
//         cout<<get<0>(das[tou])<<" "<<get<1>(das[tou])<<endl;
		if ( get<0>(das[tou]) ^ -1 )
		{
			que.push(get<0>(das[tou]));
			cnt++;
		}
		if ( get<1>(das[tou]) ^ -1 )
		{
			que.push(get<1>(das[tou]));
			cnt++;
		}
		if ( !cnt )
		{
			if ( once ) {
				cout << tou;
				once = 0;
			}
			else
				cout << " " << tou;
		}
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值