7-4 List Leaves

題目

題意:給定二叉樹上結點信息,要求按照從低到高從左到右輸出葉子結點

tip:層序遍歷

#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
vector<vector<int>>s(12,vector<int>(2));
int main() {
	int n;
	cin>>n;
	vector<int>checked(n,0);
	for(int i=0; i<n; ++i) {
		string a,b;
		cin>>a>>b;
		if(a=="-")
			s[i][0]=-1;
		else {
			checked[stoi(a)]=1;
			s[i][0]=stoi(a);
		}
		if(b=="-")
			s[i][1]=-1;
		else {
			checked[stoi(b)]=1;
			s[i][1]=stoi(b);
		}
	}
	int st=0;
	for(int i=0; i<n; ++i)
		if(!checked[i]) {
			st=i;
			break;
		}
	vector<int>ans;
	queue<int> q;
	q.push(st);
	while(!q.empty()) {
		int t=q.front();
		q.pop();
		if(s[t][0]==-1&&s[t][1]==-1)
			ans.push_back(t);//葉子結點 
		if(s[t][0]!=-1)
			q.push(s[t][0]);//左孩子 
		if(s[t][1]!=-1)
			q.push(s[t][1]);//右孩子 
	}
	cout<<ans[0];
	for(int i=1; i<ans.size(); ++i)
		cout<<" "<<ans[i];
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章