title: C++ binary search tree
body: <p>Recently I have started playing around with C++, namely classes and pointers. I looked around for similar questions, but nothing helped.</p>
  
  <p>I have a binary search tree class that holds some information in string format (well, char *), but after adding a new node to the tree, I cannot get the information back, as it returns junk.</p>
  
  <p>Here is what my code looks like:</p>
  
  <pre><code>class Node
  {
      Node *lNode;
      Node *rNode;
      char *name;
      public:
          void setName(char *n) { name = n; }
          char *getName() { return name; }
  }
  
  class Tree
  {
      Node *root;
      Node *addNode(Node *, Node *);
      public:
          Tree() { root = NULL };
          int addNewNode(Node *);
          void print();
  };
  
  int Tree::addNewNode(Node *n)
  {
      root = addNode(root, n);
      cout &lt;&lt; root-&gt;getName() &lt;&lt; endl;   // this returns the name correctly
  }
  
  Node *Tree::addNode(Node *subtree, Node *node)
  {
      if(subtree== NULL)
      {
          subtree = node;
      }
      else if(node-&gt;getName() &lt;= subtree-&gt;getLeft())
      {
          subtree-&gt;setLeft(addNode(subtree-&gt;getLeft(), node));
      }
      else
      {
          subtree-&gt;setRight(addNode(subtree-&gt;getRight(), node));
      }
  
      return subtree;
  }
  
  void Tree::print()
  {
      cout &lt;&lt; root-&gt;getName() &lt;&lt; endl;    // this does not!
  }
  </code></pre>
  
  <p>And this is where I call the methods:</p>
  
  <pre><code>Tree *myTree = new Tree();
  
  Node *n = new Node();
  n-&gt;setName(name);
  myTree-&gt;addNewNode(n);
  </code></pre>
  
  <p>The tree variable is a private member attribute of an outer container class, and actually gets created outside that class to be passed into the constructor. When I invoke the addNewNode method, that adds a Node to the tree, but when I want to print out the name of the node stored in the root, it just comes up with junk. I guess there's a haywire pointer somewhere, but I cannot find it for the life of me.</p>
  
  <p>Any help would be greatly appreciated.</p>