#include <algorithm>
#include <iostream>
#include <vector>

template <typename T> class foo
{
  T attribute1;
  std::vector<foo*> attribute2;  

 public:
  foo(const T& data):attribute1(data){}

  // Some methods

  foo* getAttribute2(int pos)const
  {
    if (pos<0 || pos>=attribute2.size()) 
        throw "In foo::getAttribute2, argument out of range";
    return attribute2[pos];
} 
  void append(foo<T>* element) {attribute2.push_back(element);}

  void foo2vector(std::vector<T>& v)
  {
    v.push_back(attribute1);
    if (attribute2.size()>0) 
    {
        for(int i=0; i<attribute2.size();i++) 
            attribute2[i]->foo2vector(v);
    }
  }

void display3()const
{
    std::vector<T> v;
    foo2vector(v);
    std::reverse(v.begin(),v.end());
    for (int i=0;i<v.size();i++)
        std::cout<<v[i]<<"\t";
}

};

int main()
{
foo<int>* root=new foo<int>(12);
root->append(new foo<int>(8)); // node 0
root->append(new foo<int>(23)); // node 1
// Sons of node 0
(root->getAttribute2(0))->append(new foo<int>(4));
(root->getAttribute2(0))->append(new foo<int>(9));
// Sons of node 1
(root->getAttribute2(1))->append(new foo<int>(17)); // node 4
root->display3();
}