title: Binary Search Tree Contains Function
body: <p>I am trying to write a "contains" function for a binary search tree. I receive the following error at compile "Unhandled exception at 0x77291CB3 (ntdll.dll) in BST.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x001E2FFC)." The following is my code.</p>
  
  <pre><code>struct Node {
      int data;
      Node* leftChild;
      Node* rightChild;
      Node() : leftChild(NULL), rightChild(NULL) {}
  };
  struct BST {
      Node* root;
      BST() : root(NULL) {}
      void insert(int value);
      bool contains(int value);
  };
  void BST::insert(int value) {
      Node* temp = new Node();
      temp-&gt;data = value;
      if(root == NULL) {
          root = temp;
          return;
      }
      Node* current;
      current = root;
      Node* parent;
      parent = root;
      current = (temp-&gt;data &lt; current-&gt;data ? (current-&gt;leftChild) : (current-&gt;rightChild)
      while(current != NULL) {
          parent = current;
          current = (temp-&gt;data &lt; current-&gt;data) ? (current-&gt;leftChild) : (current-&gt;rightChild)
      }
      if(temp-&gt;data &lt; parent-&gt;data) {
          parent-&gt;leftChild = temp;
      }
      if(temp-&gt;data &gt; parent-&gt;data) {
          parent-&gt;rightChild = temp;
      }
  }
  bool BST::contains(int value) {
      Node* temp = new Node();
      temp-&gt;data = value;
      Node* current;
      current = root;
      if(temp-&gt;data == current-&gt;data) {  // base case for when node with value is found
          std::cout &lt;&lt; "true" &lt;&lt; std::endl;
          return true;
      }
      if(current == NULL) { // base case if BST is empty or if a leaf is reached before value is found
          std::cout &lt;&lt; "false" &lt;&lt; std::endl;
          return false;
      }
      else { // recursive step
          current = (temp-&gt;data &lt; current-&gt;data) ? (current-&gt;leftChild) : (current-&gt;rightChild);
          return contains(temp-&gt;data);
      }
  }
  int main() {
      BST bst;
      bst.insert(5);
      bst.contains(4);
      system("pause");
  }
  </code></pre>
  
  <p>As it stands, I would insert a single node with value '5' and I would search the binary search tree for a node with value '4' - thus, I would expect the result to be false.</p>