title: binary search tree find if value exists
body: <p>Trying to learn tree nodes...</p>
  
  <pre><code>    Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree.
  
  Write a function that checks if a given binary search tree contains a given value.
  
  For example, for the following tree:
  
  n1 (Value: 1, Left: null, Right: null)
  n2 (Value: 2, Left: n1, Right: n3)
  n3 (Value: 3, Left: null, Right: null)
  Call to Contains(n2, 3) should return true since a tree with root at n2 contains number 3.
  </code></pre>
  
  <p>So far iv got...</p>
  
  <pre><code> public class BinarySearchTree
      {
          public static bool Contains(Node root, int value)
          {
              foreach (var v in root)
              {
                  if (root.Value == value)
                  {
                      //value found return true
                  }
              }
          }
  
          public static void Main(string[] args)
          {
              Node n1 = new Node(1, null, null);
              Node n3 = new Node(3, null, null);
              Node n2 = new Node(2, n1, n3);
  
              Console.WriteLine(Contains(n2, 3));
          }
      }
  </code></pre>
  
  <p>but root is flagging as unavailable and if I do root. I get the options tostring, value, left, right.</p>
  
  <p>Can I not iterate through a node as I would a list?
  How can I check if value is found in root?
  thank you</p>
  
  <hr>
  
  <p><strong>UPDATE</strong>
  Ahh yes OK...thanks for the reply juharr so I have updated my code to...</p>
  
  <pre><code>public static bool Contains(Node root, int value)
              {
                      if (root.Value == value)
                      {
                          return true;
                      }
                      else if (root.Value &gt; value)
                      {
                          if (root.Right == null)
                          {
                              Contains(root.Left, value);
                          }
                          Contains(root.Right, value);
                      }
                      else //(root.Value &lt; value)
                      {
                          if (root.Left == null)
                          {
                              Contains(root.Right, value);
                          }
  
                          Contains(root.Left, value);
                      }
  
                  return false;
              }
  </code></pre>
  
  <p>however on the second loop round root is null and causes a crash? </p>