public void Insert(TItem newItem)
        {
            TItem currentNodeValue = this.NodeData;

            if (currentNodeValue.CompareTo(newItem) > 0) // newItem less than current Node Value then executes
                                                         // currentNodeValue greater than newItem.
            {
                // Insert the new item into the left subtree
                if (this.LeftTree == null)
                {
                    this.LeftTree = new Binary_Tree <TItem>(newItem);
                }
                else
                {
                    this.LeftTree.Insert(newItem);      // recursive call occurs here
                    // this calls the insert method(with newItem) and the root node is the left sub
                    // Tree  of the origianl root
                }
            }
            else
            {
                // Insert the new item into the right subtree

                if (this.RightTree == null)
                {
                    this.RightTree = new Binary_Tree <TItem>(newItem);
                }
                else
                {
                    this.RightTree.Insert(newItem);
                }
            }
        }
예제 #2
0
        public static void Main(string[] args)
        {
            Binary_Tree <int> tree1 = new Binary_Tree <int>(10);

            tree1.Insert(5);
            tree1.Insert(11);
            tree1.Insert(5);
            tree1.Insert(-12);
            tree1.Insert(15);
            tree1.Insert(0);
            tree1.Insert(14);
            tree1.Insert(-8);
            string sortedData = tree1.WalkTree();

            Console.WriteLine("Sorted data is: {0}", sortedData);
            // in  order traversal

            Binary_Tree <string> tree2 = new Binary_Tree <string>("Hello");

            tree2.Insert("World");
            tree2.Insert("How");
            tree2.Insert("Are");
            tree2.Insert("You");
            tree2.Insert("Today");
            tree2.Insert("I");
            tree2.Insert("Hope");
            tree2.Insert("You");
            tree2.Insert("!");
            sortedData = tree2.WalkTree();
            Console.WriteLine("Sorted data is: {0}", sortedData);
        }
        }                                                //set; }



        public Binary_Tree(TItem nodeValue) //constructor       hree nodeValue is the root node
        {
            this.NodeData  = nodeValue;
            this.LeftTree  = null;
            this.RightTree = null;
        }