PAT1004 Counting Leaves

开始想用树来做,就构造了TreeNode。结果完全没用上,用map和vector就能很好解决问题,本题放在pat里确实算很简单的了。

#include 
#include 
//#include 
#include 

using namespace std;
struct TreeNode{
    int val;
    TreeNode* leftchild;
    TreeNode* rightchild;
    TreeNode():val(0),leftchild(NULL),rightchild(NULL){}
    TreeNode(int v):val(v),leftchild(NULL),rightchild(NULL){}
};
int main()
{
    int totalNode, parentNode;
    cin>>totalNode>>parentNode;
    map<int,vector<int> > relationship;
    for(int i = 0; i < parentNode; i++){
        int nodeVal, childNum;
        cin>>nodeVal>>childNum;

        for(int j = 0; j < childNum; j++){
            int childVal;
            cin>>childVal;
            relationship[nodeVal].push_back(childVal);
        }
    }
    int countCur = 0;
    vector<int> nextdepthNode;
    vector<int> curdepthNode = relationship[1];
    if(curdepthNode.empty()) cout<<1;
    else{
        cout<<0;
        while(!curdepthNode.empty()){
            int countNoChild = 0;
            for(int i = 0; i < curdepthNode.size();i++){
                if(relationship[curdepthNode[i]].empty()) countNoChild++;
                else nextdepthNode.insert(nextdepthNode.end(),relationship[curdepthNode[i]].begin(),relationship[curdepthNode[i]].end());
            }
            cout<<" "<<countNoChild;
            curdepthNode = nextdepthNode;
            vector<int> New;
            nextdepthNode = New;
        }
    }
    return 0;
}

你可能感兴趣的:(数据结构)