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

posted @ 2022-11-01 01:50  noob-lian  阅读(86)  评论(0)    收藏  举报
Language: