Exemplo n.º 1
0
        /// <summary>
        ///     Insert specified data into Binary search tree
        /// </summary>
        /// <param name="data"> the data need to be inserted </param>
        /// <returns> a boolean value indicate if the insertion is successful </returns>
        public override bool Insert(T data)
        {
            if (Root == null)
            {
                Root = new BstNode <T>(data);
                TreeSize++;
                return(true);
            }

            var current = Root;

            while (true)
            {
                if (data.CompareTo(current.Data) < 0)
                {
                    if (current.Left != null)
                    {
                        current = current.Left;
                        continue;
                    }

                    current.Left = new BstNode <T>(data);
                    TreeSize++;
                    return(true);
                }

                //Duplicate data is not allowed in BST, if found, stop insertion and return false;
                if (data.CompareTo(current.Data) == 0)
                {
                    return(false);
                }
                if (current.Right != null)
                {
                    current = current.Right;
                    continue;
                }

                current.Right = new BstNode <T>(data);
                TreeSize++;
                return(true);
            }
        }
Exemplo n.º 2
0
 /// <summary>
 ///     Constructor: Creates an Binary search with Root node holds specified data
 ///     since standard Binary Search does not have any re-balancing algorithm, the root node will not change.
 /// </summary>
 /// <param name="data"> Data will be hold by Root node </param>
 public Bst(T data)
 {
     Root = new BstNode <T>(data);
     TreeSize++;
 }