title: tree data structure with list in c++
body: <p>I implemented a tree structure in c++, referring to other people's codes. The code below I made was surely compiled and seem to work well. But I suspect that there are better ways. For example, is this code safe in the point of memory leak? Is there any simpler and computationally more efficient way?</p>
  
  <p>Specifically, I doubt the necessity of the "std::list lst_nodes".
  The expand_node function in Tree class attaches a new node to a parent node the value of which is closest to that of the new node. This process requires iteration over all the existing nodes to access their values. For this iteration purpose, I defined a member variable named "std::list lst_nodes" in Tree class. And I susplect there may exists a neat way to do the same without defining lst_nodes.</p>
  
  <pre><code>#include&lt;random&gt;
  #include&lt;iostream&gt;
  #include&lt;list&gt;
  using namespace std;
  
  class Node{
    public:/*functions*/
      Node(const double&amp; val_, Node* parent_=nullptr)
        :val(val_), parent(parent_)
      {
        if(parent){
          parent-&gt;children.push_back(this);
        }
      }
    public:/*variables*/
      Node* parent;
      std::list&lt;Node*&gt; children;
      double val;
  };
  
  class Tree{
    public:/*function*/
      Tree(double x_init);
      void extend_node();
  
    public:/*variables*/
      list&lt;Node*&gt; lst_nodes;
      double x_init;
  };
  
  Tree::Tree(double x_init_)
    :x_init(x_init_)
  {
    Node* n=new Node(x_init);
    lst_nodes.push_back(n);
  }
  
  void Tree::extend_node(){
    double val_new = rand();
    auto it=lst_nodes.begin();
    double minval = abs((**it).val-val_new);
    Node* node_parent;
    for(;it!=lst_nodes.end(); it++){
      if(minval&gt;abs((**it).val-val_new)){
        minval = abs((**it).val-val_new);
        node_parent = *it;
      }
    }
    Node* n_new = new Node(val_new, node_parent);
    node_parent-&gt;children.push_back(n_new);
    lst_nodes.push_back(n_new);
  }
  
  int main(){
    Tree t(0);
    for(int i=0; i&lt;100; i++){
      t.extend_node();
    }
  }
  </code></pre>
  
  <p>Thanks a lot.</p>