Example #1
0
 /// <summary>
 /// Recursively inserts node into tree
 /// </summary>
 /// <remarks>
 /// Logic uses makes sure to maintain BST rules
 /// </remarks>
 /// <param name="key"></param>
 /// <param name="leaf"></param>
 public static void RunRecursively(int key, TreeNode leaf)
 {
     // check if value is less the node, go left
     if (key < leaf.key)
     {
         if (leaf.left != null)
         {
             RunRecursively(key, leaf.left);  // check left child
         }
         else
         {
             leaf.left = new TreeNode();             // else assign as left child
             (leaf.left).key = key;
         }
     }
     // else if value is greater than node, go right
     else if (key >= leaf.key)
     {
         if (leaf.right != null)
         {
             RunRecursively(key, leaf.right);    // check if right child
         }
         else
         {
             leaf.right = new TreeNode();            // else assign as right child
             (leaf.right).key = key;
         }
     }
 }
Example #2
0
        /// <summary>
        /// Creates a BST
        /// </summary>
        /// <param name="values"></param>
        /// <param name="root"></param>
        public static void CreateBinarySearchTree(int[] values, out TreeNode root)
        {
            if (values == null || values.Length ==0)
            {
                throw new System.ArgumentException("CreateTree error, values must contain one element.");
            }

            root = new TreeNode();
            root.key = values[0];

            for (int i=0; i<values.Length; i++)
            {
                InsertTreeNode.RunRecursively(values[i], root);
            }
        }