public static void main()
        {
            BST<int> bst = new BST<int>();
            bst.add(20);
            bst.add(8);
            bst.add(22);
            bst.add(4);
            bst.add(12);
            bst.add(10);
            bst.add(14);


            //bst.breadthFirstTraversal();

            Node<int> node = LowestCommonAncestor.FindCommonAncestor(bst, 4, 14);
            Console.WriteLine(node.Element);//8

            Node<int> node2 = LowestCommonAncestor.FindCommonAncestor(bst, 10, 14);
            Console.WriteLine(node2.Element); //12

            Node<int> node3 = LowestCommonAncestor.FindCommonAncestor(bst, 8, 22);
            Console.WriteLine(node3.Element); //20

            Node<int> node4 = LowestCommonAncestor.FindCommonAncestor(bst, 4, 22);
            Console.WriteLine(node4.Element);//20

            Node<int> node5 = LowestCommonAncestor.FindCommonAncestor(bst, 4, 8);
            Console.WriteLine(node5.Element); //20
        }
Example #2
0
 static void Main(string[] args)
 {
     BST<int> bst = new BST<int>();
     //Testing add
     Console.WriteLine("Testing Add function");
     int[] add = new int[] { 35, 50, 10, 15, 55, 1, 37 };
     foreach (int i in add) {
         bst.Insert(i);
         Console.WriteLine("\t" + i + "added ");
     }
     Console.WriteLine("\n Add function finished");
     bst.PreTraversal(BSTPrint);
     if (bst.Contains(55)) {
         Console.WriteLine("\n BST Contains 55");
     }
     if (bst.Contains(10)) {
         Console.WriteLine("\n BST contains 10");
     }
     bst.Remove(10);
     if (!bst.Contains(10)) {
         Console.WriteLine("\n Remove Successfull");
     }
     else {
         Console.WriteLine("\n Could not remove 10");
     }
     bst.PreTraversal(BSTPrint);
     Console.ReadLine();
 }
        public static void Main()
        {
            var tree = new BST<int>(7);

            // tree.Insert(7);
            tree.Insert(2);
            tree.Insert(3);
            tree.Insert(12);
            tree.Insert(29);
            tree.Insert(1);

            Console.WriteLine(tree);
            Console.WriteLine("The root is {0}", tree.Root.Value);

            bool isFound = BST<int>.Search(16, tree.Root);
            Console.WriteLine(isFound);
            Console.WriteLine();

            tree.Remove(16);
            Console.WriteLine(tree);

            var anotherTree = tree.Clone();
            Console.WriteLine(anotherTree);

            Console.WriteLine(anotherTree.Equals(tree));
        }
        public SymbolGraph(string[] graphData, char sp)
        {
            st = new BST<string, string>();

            for (int i = 0; i < graphData.Length; i++)
            {
                string[] a = graphData[i].Split(sp);
                foreach (string s in a)
                {
                    if (!st.Contains(s))
                    {
                        st.Put(s, st.Size().ToString());
                    }
                }
            }

            keys = new string[st.Size()];

            foreach (string key in st.Keys())
            {
                keys[int.Parse(st.Get(key))] = key;
            }

            graph = new Graph(st.Size());

            foreach (string data in graphData)
            {
                string[] a = data.Split(sp);
                int v = int.Parse(st.Get(a[0]));
                for (int i = 1; i < a.Length; i++)
                {
                    graph.AddEdge(v, int.Parse(st.Get(a[i])));
                }
            }
        }
        public void BalancedTests()
        {
            var input = new BST<int>(5);

            input.Insert(3);
            input.Insert(1);
            input.Insert(4);
            input.Insert(2);

            input.Insert(7);
            input.Insert(6);
            input.Insert(8);
            input.Insert(9);

            Assert.IsTrue(input.IsBalanced());

            input = new BST<int>(5);

            input.Insert(3);
            input.Insert(1);
            input.Insert(4);
            input.Insert(2);

            input.Insert(7);
            input.Insert(6);
            input.Insert(8);

            Assert.IsTrue(input.IsBalanced());
        }
        public void NotBalancedTests()
        {
            var input = new BST<int>(10);

            input.Insert(3);
            input.Insert(1);
            input.Insert(4);
            input.Insert(2);

            input.Insert(7);
            input.Insert(6);
            input.Insert(8);
            input.Insert(9);

            Assert.IsFalse(input.IsBalanced());

            input = new BST<int>(0);

            input.Insert(3);
            input.Insert(1);
            input.Insert(4);
            input.Insert(2);

            input.Insert(7);
            input.Insert(6);
            input.Insert(8);
            input.Insert(9);

            Assert.IsFalse(input.IsBalanced());

            input = new BST<int>(2);

            input.Insert(3);
            input.Insert(1);
            input.Insert(4);
            input.Insert(2);

            input.Insert(7);
            input.Insert(6);
            input.Insert(8);
            input.Insert(9);

            Assert.IsFalse(input.IsBalanced());

            input = new BST<int>(7);

            input.Insert(3);
            input.Insert(1);
            input.Insert(4);
            input.Insert(2);

            input.Insert(7);
            input.Insert(6);

            Assert.IsFalse(input.IsBalanced());
        }
        //Returns true if the given tree is a BST and its
        //values are >= min and <= max.
        private static bool recIsBST(BST.BSTNode node, int min, int max)
        {
            if (node == null) return true;

            // false if this node violates the min/max constraint
            if (node.data < min || node.data > max)
                return false;

            // otherwise check the subtrees recursively,
            // tightening the min or max constraint
            return recIsBST(node.left, min, node.data) && recIsBST(node.right, node.data, max);
        }
Example #8
0
        static void Main(string[] args)
        {
            BST<int, string> bst = new BST<int, string>();
            bst.put(5, "Alex");
            bst.put(4, "Anna");
            bst.put(3, "Aliona");
            bst.put(2, "Sergey");
            bst.put(1, "Olga");

            bst.print();

            Console.ReadKey();
        }
Example #9
0
File: P2x.cs Project: Kablamz/BST
        static void Main(string[] args)
        {
            BST<int> binary = new BST<int>();
            /*
                                                [80]
             *                        [60]                   [100]
             *                  [40]         [75]       [95]           [120]
             *               [20]  [50]  [65]        [85]           [110]   [140]
             */

            binary.Insert(80);//insert list of numbers
            binary.Insert(60);
            binary.Insert(40);
            binary.Insert(20);
            binary.Insert(100);
            binary.Insert(120);
            binary.Insert(140);
            binary.Insert(75);
            binary.Insert(50);
            binary.Insert(65);
            binary.Insert(90);
            binary.Insert(95);
            binary.Insert(85); //deleted
            binary.Insert(110);

            binary.Delete(90); //delete 85 and rearrange

            Console.Write("Display level order: "); //extra credit
            binary.DisplayLevelOrder();
            Console.WriteLine();
            Console.WriteLine("Width: {0}", binary.GetWidth());

            Console.WriteLine("Empty tree? {0}", binary.Empty());//check for empty, should be false
            Console.WriteLine("Search: {0}",binary.Search(110)); //search for 110 should be true
            Console.WriteLine("Number of nodes in tree: {0}",binary.NumNodes()); //find number of nodes through count 14 - 1 nodes
            Console.WriteLine("Number of leaf nodes in tree: {0}", binary.NumLeafNodes()); // find nodes with no children 6
            Console.WriteLine("Height of tree: {0}", binary.GetHeight()); //get height of the tree not including root, should be 4
            Console.WriteLine("Level Search: {0}", binary.Level(65)); //search how fr down 65 is which is 3 down

            binary.DisplayInOrder(); //display in order
            Console.WriteLine();
            binary.DisplayPreOrder(); //display pre order
            Console.WriteLine();
            binary.DisplayPostOrder(); //display post order
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Ancestors: {0}", binary.DisplayAncestors(85));//should be 95 100 and 80 behind it from the tree

            Console.ReadKey();
        }
Example #10
0
        static void Main(string[] args)
        {
            BST<int,string> bst=new BST<int, string>();
            bst.put(5,"Alex");
            bst.put(4,"Anna");
            bst.put(6, "Aliona");
            bst.put(3,"Sergey");
            bst.put(7,"Olga");

            bst.print();

            Console.WriteLine("Max : {0}", bst.max());
            Console.WriteLine("Min : {0}", bst.min());

            Console.ReadKey();
        }
Example #11
0
        private bool recAreSame(BST.BSTNode node1, BST.BSTNode node2)
        {
            //when both empty they are same
            if (node1 == null && node2 == null) return true;
            //if (node1 == null && node2 != null) return false;
            //if (node1 != null && node2 == null) return false;

            if (node1 != null && node2 != null)
            {
                return node1.data == node2.data && //same data value
                       recAreSame(node1.left, node2.left) && //compare left
                       recAreSame(node1.right, node2.right); //compare right
            }
            //not same
            return false;
        }
Example #12
0
        static void Graph()
        {
            BST<int> tree = new BST<int>();
            tree.InOrder();
            tree.Insert(87);
            tree.InOrder();

            tree.Insert(new int[] { 234, 632, 123, 654, 1, 354, 0 });
            tree.InOrder();
            tree.PreOrder();
            tree.PostOrder();

            tree.LevelOrder();

            tree.DFT();
            tree.BFT();
        }
Example #13
0
 static void Main()
 {
     BST<int> test = new BST<int>();
     test.Insert(5);
     test.Insert(2);
     test.Insert(4);
     test.Insert(6);
     test.Insert(8);
     test.Insert(9);
     test.Insert(1);
     test.Insert(11);
     test.Insert(3);
     Console.WriteLine("My test tree:\t{0}", test);
     Console.WriteLine("Hash code:\t{0}", test.GetHashCode());
     BST<int> testClone = test.Clone();
     Console.WriteLine("The original and the clone are equal: {0}", test.Equals(testClone));
     Console.WriteLine("Change in clone - insert value 10:");
     testClone.Insert(10);
     Console.WriteLine("Clone:\t\t{0}", testClone);
     Console.WriteLine("Original:\t{0}", test);
     Console.WriteLine("Contains 3:\t{0}", test.Search(3));
     Console.WriteLine("Contains 13:\t{0}", test.Search(13));
     Console.WriteLine();
     Console.WriteLine("My test tree:\t{0}", test);
     int value = 3;
     Console.WriteLine("Remove number {0}:", value);
     test.Remove(value);
     Console.WriteLine("My test tree:\t{0}", test);
     value = 2;
     Console.WriteLine("Remove number {0}:", value);
     test.Remove(value);
     Console.WriteLine("My test tree:\t{0}", test);
     value = 5;
     Console.WriteLine("Remove number {0}:", value);
     test.Remove(value);
     Console.WriteLine("My test tree:\t{0}", test);
     value = 9;
     Console.WriteLine("Remove number {0}:", value);
     test.Remove(value);
     Console.WriteLine("My test tree:\t{0}", test);
     value = 11;
     Console.WriteLine("Remove number {0}:", value);
     test.Remove(value);
     Console.WriteLine("My test tree:\t{0}", test);
 }
Example #14
0
 static void Main(string[] args)
 {
     var treeForString = new BST<int, string>();
     var stackOfValues = new Stack<string>();
     GetInitialValuesFromArgs(args, ref stackOfValues);
     while(stackOfValues.Count != 0)
     {
         var value = stackOfValues.Pop();
         treeForString.Insert(GetKeyFromString(value), value);
     }
     Console.Write(treeForString.ToString());
     string val;
     var key = 6;
     Console.Write("Find: key = " + key);
     var b = treeForString.TryFind(6, out val);
     Console.WriteLine(", value = "+val);
     Console.ReadKey();
 }
Example #15
0
        private int CalculateRangeNum(BST aBst, int pre, int lower, int upper)
        {
            int coun = 0;

            if (aBst == null)
            {
                return coun;
            }

            if (aBst.Value < lower)
            {
                coun += CalculateRangeNum(aBst.Right, aBst.Value, lower, upper);
            }
            else if (aBst.Value > upper)
            {
                coun += CalculateRangeNum(aBst.Left, aBst.Value, lower, upper);
            }
            else if (aBst.Value >= lower && aBst.Value <= upper)
            {
                coun++;
                coun += CalculateRangeNum(aBst.Right, aBst.Value, lower, upper);
                coun += CalculateRangeNum(aBst.Left, aBst.Value, lower, upper);
            }

            if (pre != 0)
            {
                if (pre + aBst.Value < lower)
                {
                    coun += CalculateRangeNum(aBst.Right, aBst.Value, lower, upper);
                }
                else if (pre + aBst.Value > upper)
                {
                    coun += CalculateRangeNum(aBst.Left, aBst.Value, lower, upper);
                }
                else if (pre + aBst.Value >= lower && pre + aBst.Value <= upper)
                {
                    coun++;
                    coun += CalculateRangeNum(aBst.Right, aBst.Value, lower, upper);
                    coun += CalculateRangeNum(aBst.Left, aBst.Value, lower, upper);
                }
            }

            return coun;
        }
Example #16
0
    static void Main()
    {
        BST<int, string> firstTree = new BST<int, string>();
        firstTree.Add(4, "4");
        firstTree.Add(12, "12");
        firstTree.Add(1, "1");
        firstTree.Add(8, "8");
        firstTree.Add(5, "5");

        foreach (var node in firstTree)
        {
            Console.WriteLine(node.Key + " " + node.Value);
        }
        Console.WriteLine();

        firstTree.Remove(8);
        BST<int, string> secondTree = (BST<int, string>)firstTree.Clone();

        Console.WriteLine(firstTree);
        Console.WriteLine(secondTree);

        BST<int, string> thirdTree = new BST<int, string>();
        thirdTree.Add(5, "10");
        Console.WriteLine(thirdTree);

        Console.WriteLine(firstTree.Equals(secondTree));
        Console.WriteLine(object.ReferenceEquals(firstTree, secondTree));
        Console.WriteLine(firstTree.Equals(thirdTree));
        Console.WriteLine(object.ReferenceEquals(firstTree, thirdTree));

        thirdTree.Add(8, "16");
        thirdTree.Add(1, "2");
        thirdTree.Add(12, "24");
        thirdTree.Add(4, "8");
        Console.WriteLine(thirdTree);

        Console.WriteLine(firstTree.Equals(thirdTree));
        Console.WriteLine(object.ReferenceEquals(firstTree, thirdTree));

        BST<int, string> fourthTree = new BST<int, string>();
        fourthTree.Add(1, "1");
        fourthTree.Add(1, "one");
        Console.WriteLine(fourthTree);
    }
Example #17
0
	public static void Test(){
		var root1 = new Node(1);
		root1.Left = new Node(2);
		root1.Right = new Node(3);
		root1.Left.Left = new Node(4);
		root1.Left.Right = new Node(5);
		root1.Right.Left = new Node(6);
		root1.Right.Right = new Node(7);
		var bst = new BST();
		var root2 = new Node(8);
		root2.Left = new Node(5);
		root2.Right = new Node(11);
		root2.Left.Left = new Node(4);
		root2.Left.Right = new Node(6);
		root2.Right.Left = new Node(10);
		root2.Right.Right = new Node(13);
		Console.WriteLine(bst.Valdiate(root1));
		Console.WriteLine(bst.Valdiate(root2));
	}
Example #18
0
        public void TestBst() {
            var bst = new BST<string, string>();
            bst.Put("A", "A");
            bst.Put("B", "B");
            bst.Put("C", "C");
            bst.Put("D", "D");
            bst.Put("E", "E");
            bst.Put("F", "F");
            bst.Put("G", "G");
            bst.Put("H", "H");
            bst.Put("I", "I");
            bst.Put("J", "J");

            Assert.IsFalse(bst.IsEmpty);
            Assert.AreEqual(10, bst.Count);
            Assert.AreEqual(9, bst.Height);

            StdOut.WriteLine(bst.LevelOrder());
        }
        static void Main(string[] args)
        {
            var bst           = new BST <string, int>();
            var tale          = BinarySearchTree.Properties.Resources.tale.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            var distinctCount = FrequencyCounter.CountDistinct(tale, bst);

            Console.WriteLine("distinctCount: " + distinctCount);

            // 二叉查找树的内存开销 = 对象开销 + 根结点引用 + N个结点
            //     = 对象开销 + 根结点引用 + N×(对象开销 + 父类型引用 + 左 / 右子树引用 + 键 / 值引用 + 结点数)
            //     = 16 + 8 + N×(16 + 8 + 16 + 16 + 4 + 4) = 24 + 64N 字节

            // BinarySearchST:对象开销 + 键 / 值数组引用 + 键 / 值数组 + 计数器(一个 int)。
            //     = 16 + 16 + (16 + 4 + 4 + 8N)×2 + 4 + 4 = 88 + 16N 字节。

            // SequentialSearchST:对象开销 + 头结点引用 + N个结点 + 计数器
            //     = 对象开销 + 头结点引用 + N×(对象开销 + 父类型引用 + next引用 + 键 / 值引用) + 计数器
            //     = 16 + 8 + N×(16 + 8 + 8 + 16) + 4 + 4 = 32 + 48N 字节

            // 《双城记》中不重复的单词有 26436 个(不包括最后的版权声明),全部是原文的子字符串,每个占 40 字节。
            // 一个 Integer 占 24 字节,于是估计的内存消耗为:24 + (64 + 40 + 24)×26436 = 3383832 字节。
        }
Example #20
0
        public void TestDelete_12()
        {
            BST <int> btree = GetTree();

            Assert.AreEqual(true, btree.AddKeyValue(7, 200));
            Assert.AreEqual(true, btree.AddKeyValue(5, 200));

            btree.DeleteNodeByKey(4);
            Assert.AreEqual(false, btree.FindNodeByKey(4).NodeHasKey);

            // Преемник и его предок
            //
            Assert.AreEqual(8, btree.FindNodeByKey(5).Node.Parent.NodeKey);
            Assert.AreEqual(5, btree.FindNodeByKey(5).Node.Parent.LeftChild.NodeKey);
            Assert.AreEqual(null, btree.FindNodeByKey(5).Node.Parent.RightChild);
            Assert.AreEqual(16, btree.FindNodeByKey(5).Node.Parent.Parent.NodeKey);
            Assert.AreEqual(2, btree.FindNodeByKey(5).Node.Parent.LeftChild.LeftChild.NodeKey);
            Assert.AreEqual(6, btree.FindNodeByKey(5).Node.Parent.LeftChild.RightChild.NodeKey);

            // Новые потомки преемника
            //
            Assert.AreEqual(2, btree.FindNodeByKey(5).Node.LeftChild.NodeKey);
            Assert.AreEqual(5, btree.FindNodeByKey(5).Node.LeftChild.Parent.NodeKey);
            Assert.AreEqual(3, btree.FindNodeByKey(5).Node.LeftChild.RightChild.NodeKey);
            Assert.AreEqual(1, btree.FindNodeByKey(5).Node.LeftChild.LeftChild.NodeKey);

            Assert.AreEqual(6, btree.FindNodeByKey(5).Node.RightChild.NodeKey);
            Assert.AreEqual(5, btree.FindNodeByKey(5).Node.RightChild.Parent.NodeKey);
            Assert.AreEqual(7, btree.FindNodeByKey(5).Node.RightChild.RightChild.NodeKey);
            Assert.AreEqual(null, btree.FindNodeByKey(5).Node.RightChild.LeftChild);

            // Простой поиск узлов после удаления
            //
            Assert.AreEqual(true, btree.FindNodeByKey(7).NodeHasKey);
            Assert.AreEqual(true, btree.FindNodeByKey(6).NodeHasKey);
            Assert.AreEqual(true, btree.FindNodeByKey(3).NodeHasKey);
            Assert.AreEqual(true, btree.FindNodeByKey(2).NodeHasKey);
            Assert.AreEqual(true, btree.FindNodeByKey(1).NodeHasKey);
        }
Example #21
0
        static void Main(string[] args)
        {
            BST  bst  = new BST();
            Node root = null;

            root = bst.Insert_Recursive(root, 50);
            bst.Insert_Recursive(root, 30);
            bst.Insert_Recursive(root, 20);
            bst.Insert_Recursive(root, 40);
            bst.Insert_Recursive(root, 70);
            bst.Insert_Recursive(root, 60);
            bst.Insert_Recursive(root, 80);

            var root2 = bst.DeleteNode(root, 20);

            bst.Insert_Recursive(root, 20);

            //Node with both the childs
            var root1 = bst.DeleteNode(root, 50);

            bst.Insert_Recursive(root, 50);
        }
Example #22
0
        public void AddKeyValue_If_Node_Already_Exists()
        {
            BST <string> testBSTree = new BST <string>(new BSTNode <string>(8, "Root", null));

            bool isAdded1 = testBSTree.AddKeyValue(4, "Level_1 Left_Child");
            bool isAdded2 = testBSTree.AddKeyValue(12, "Level_1 Right_Child");
            bool isAdded3 = testBSTree.AddKeyValue(2, "Level_2 Left_Child");
            bool isAdded4 = testBSTree.AddKeyValue(6, "Level_2 Right_Child");
            bool isAdded5 = testBSTree.AddKeyValue(10, "Level_2 Left_Child");
            bool isAdded6 = testBSTree.AddKeyValue(14, "Level_2 Right_Child");
            bool isAdded7 = testBSTree.AddKeyValue(6, "Level_2 Right_Child"); // попытка добавления ключа который уже присутствует в дереве

            Assert.IsTrue(isAdded1);
            Assert.IsTrue(isAdded2);
            Assert.IsTrue(isAdded3);
            Assert.IsTrue(isAdded4);
            Assert.IsTrue(isAdded5);
            Assert.IsTrue(isAdded6);

            Assert.IsFalse(isAdded7); // ключ-дубликат не добавлен
            Assert.IsTrue(testBSTree.Count() == 7);
        }
Example #23
0
        private static void SolveQuestionTwo()
        {
            Console.WriteLine("Enter a list of Integers separated by ',' and press ENTER when Finished: ");
            string[]  numbersEntered = Console.ReadLine().Split(',');
            BST <int> bst            = new BST <int>();

            // Reads all the numbers and put them into the BST.
            foreach (string number in numbersEntered)
            {
                if (!int.TryParse(number.Trim(), out int validNumber))
                {
                    Console.WriteLine("The list entered is either empty or contains one or more invalid numbers. Exiting the application!");
                    return;
                }

                bst.Insert(validNumber);
            }

            Console.WriteLine();
            Console.Write("Level Order: ");
            bst.LevelOrderPrint();
        }
Example #24
0
        public void DeleteTest()
        {
            IEnumerable <long> preOrderList = new List <long>()
            {
                5, -1, 23, 17, 10, -1, 15, -1, -1, 21, 20,
                -1, -1, -1, 35, 30, 25, -1, -1, -1, -1
            };

            var root = BST.ParseBST(ref preOrderList);
            var st   = new SplayTree(root);

            Assert.AreEqual("5(-,23(17(10(-,15),21(20,-)),35(30(25,-),-)))", st.ToString());

            st.Delete(25);
            Assert.AreEqual("30(23(5(-,17(10(-,15),21(20,-))),-),35)", st.ToString());

            st.Delete(15);
            Assert.AreEqual("17(10(5,-),30(23(21(20,-),-),35))", st.ToString());

            st.Delete(12);
            Assert.AreEqual("17(10(5,-),30(23(21(20,-),-),35))", st.ToString());
        }
Example #25
0
        // On Process
        public override void Test()
        {
            BST bst = new BST();

            bst.Insert(5);
            bst.Insert(1);
            bst.Insert(7);
            BSTSequence(bst.Root, 0, new List <int[]> {
                new int[] { bst.Root.Value }
            });
            bst = new BST();
            bst.Insert(5);
            bst.Insert(3);
            bst.Insert(7);
            bst.Insert(1);
            bst.Insert(4);
            bst.Insert(6);
            bst.Insert(9);
            BSTSequence(bst.Root, 0, new List <int[]> {
                new int[] { bst.Root.Value }
            });
        }
Example #26
0
        public void FinMinMax_in_SubTree_if_Tree_Has_15_Nodes()
        {
            BST <string> testBSTree = new BST <string>(new BSTNode <string>(8, "Root", null));

            bool isAdded1 = testBSTree.AddKeyValue(4, "Level_1 Left_Child");
            bool isAdded2 = testBSTree.AddKeyValue(12, "Level_1 Right_Child");

            Assert.IsTrue(testBSTree.Count() == 3);

            bool isAdded3 = testBSTree.AddKeyValue(2, "Level_2 Left_Child");
            bool isAdded4 = testBSTree.AddKeyValue(6, "Level_2 Right_Child");
            bool isAdded5 = testBSTree.AddKeyValue(10, "Level_2 Left_Child");
            bool isAdded6 = testBSTree.AddKeyValue(14, "Level_2 Right_Child");

            Assert.IsTrue(testBSTree.Count() == 7);

            bool isAdded7  = testBSTree.AddKeyValue(1, "Level_3 Left_Child");
            bool isAdded8  = testBSTree.AddKeyValue(3, "Level_3 Right_Child");
            bool isAdded9  = testBSTree.AddKeyValue(5, "Level_3 Left_Child");
            bool isAdded10 = testBSTree.AddKeyValue(7, "Level_3 Right_Child");
            bool isAdded11 = testBSTree.AddKeyValue(9, "Level_3 Left_Child");
            bool isAdded12 = testBSTree.AddKeyValue(11, "Level_3 Right_Child");
            bool isAdded13 = testBSTree.AddKeyValue(13, "Level_3 Left_Child");
            bool isAdded14 = testBSTree.AddKeyValue(15, "Level_3 Right_Child");

            Assert.IsTrue(testBSTree.Count() == 15);

            BSTFind <string> foundFromNode = testBSTree.FindNodeByKey(12);

            int expectedMin = 9;
            int expectedMax = 15;

            BSTNode <string> minValue = testBSTree.FinMinMax(foundFromNode.Node, false);
            BSTNode <string> maxValue = testBSTree.FinMinMax(foundFromNode.Node, true);

            Assert.AreEqual(expectedMin, minValue.NodeKey);
            Assert.AreEqual(expectedMax, maxValue.NodeKey);
        }
Example #27
0
        static void Main(string[] args)
        {
            int[] K = new int[10] {
                1, 2, 3, 4, 5, 0, 0, 0, 0, 0
            };

            int[] M = new int[5] {
                1, 2, 4, 5, 7
            };

            //int k = Array.BinarySearch(M, 8);
            //int index = ~k;
            Array.Array.Merge(K, 5, M, 5);
            int N = 1000000;

            int[]  nums   = new int[N];
            Random random = new Random(100);

            for (int i = 0; i < N; i++)
            {
                nums[i] = random.Next();
            }

            Sort.Sort.InsertionSort(nums);

            BST <int, int> bst = new BST <int, int>();

            for (int i = 0; i < nums.Length; i++)
            {
                bst.Put(nums[i], i);
            }
            var result = bst.Min();
            var min    = nums.Min();

            Console.WriteLine(result);
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
Example #28
0
        public void Add_GivenDataLessThanRoot_ExpectNewNodeInLeftSubTree()
        {
            //Given
            var expected = new BST {
                Root = new Node(3)
            };

            expected.Root.Left      = new Node(2);
            expected.Root.Right     = new Node(4);
            expected.Root.Left.Left = new Node(1);
            var tree = new BST {
                Root = new Node(3)
            };

            tree.Root.Left  = new Node(2);
            tree.Root.Right = new Node(4);

            //When
            tree.Add(1);

            //Then
            tree.Should().BeEquivalentTo(expected);
        }
        static void Main(string[] args)
        {
            string[] worstInput =
            {
                "A X C S E R H",
                "X A S C R E H",
                "A C E H R S X",
                "X S R H E C A",
                "X A S R H E C",
                "A X S R H E C"
            };

            foreach (var worst in worstInput)
            {
                var keys = worst.Split(' ');
                var bst  = new BST <string, string>();
                foreach (var key in keys)
                {
                    bst.Put(key, key);
                }
                Console.WriteLine(bst);
            }
        }
Example #30
0
        /// <summary>
        /// Crteate a decision tree that maps a character into a partion block id
        /// </summary>
        /// <param name="solver">character alberbra</param>
        /// <param name="partition">partition of the whole set of all characters into pairwise disjoint nonempty sets</param>
        /// <param name="precomputeLimit">upper limit for block ids for characters to be precomputed in an array (default is 0xFF, i.e. extended ASCII)</param>
        /// <returns></returns>
        internal static DecisionTree Create(CharSetSolver solver, BDD[] partition, ushort precomputeLimit = 0xFF)
        {
            if (partition.Length == 1)
            {
                //there is no actual partition, everything maps to one id 0, e.g. as in .*
                return(new DecisionTree(new int[(int)precomputeLimit], new BST(0, null, null)));
            }

            if (precomputeLimit == 0)
            {
                return(new DecisionTree(new int[] { }, MkBST(new PartitionCut(solver, partition), 0, 0xFFFF)));
            }

            int[] precomp = Precompute(solver, partition, precomputeLimit);
            BST   bst     = null;

            if (precomputeLimit < ushort.MaxValue)
            {
                bst = MkBST(new PartitionCut(solver, partition), precomputeLimit + 1, ushort.MaxValue);
            }

            return(new DecisionTree(precomp, bst));
        }
Example #31
0
        public void TestDeepMode1_2()
        {
            BST <int> bst = GetBST();

            bst.AddKeyValue(-2, 200);
            bst.AddKeyValue(1, 200);
            bst.AddKeyValue(11, 200);
            bst.AddKeyValue(22, 200);
            bst.AddKeyValue(21, 200);

            List <BSTNode <int> > list = bst.DeepAllNodes(1);

            int[] keys    = new int[] { 1, -2, 6, 3, 9, 11, 12, 10, 8, 19, 21, 22, 23, 20, 16 };
            int   counter = 0;

            Assert.AreEqual(15, list.Count);

            foreach (BSTNode <int> node in list)
            {
                Assert.AreEqual(keys[counter], node.NodeKey);
                counter++;
            }
        }
Example #32
0
        public void TestBST()
        {
            var bst = new BST <int>();

            bst.Add(10);
            bst.Add(11);
            bst.Add(9);


            Assert.Equal(new int[] { 10, 9, 11 }, bst.LevelOrder());

            var tree = new TreeNode <int>(3);

            tree.Right = new TreeNode <int>(4);
            tree.Left  = new TreeNode <int>(1);

            tree.Left.Left  = new TreeNode <int>(2);
            tree.Left.Right = new TreeNode <int>(5);

            Assert.False(BST <int> .Test(tree));

            Assert.True(BST <int> .Test(bst.GetRoot));
        }
        static public int FindClosestValueInBstV3(BST tree, int target)
        {
            var nextToVisit = new Queue <BST>();
            int closest     = tree.value;

            nextToVisit.Enqueue(tree);

            while (nextToVisit.Any() && nextToVisit.Peek() != null)
            {
                var node = nextToVisit.Dequeue();
                closest = (Math.Abs(target - node.value) > Math.Abs(target - closest)) ? closest : node.value;

                if (target > node.value)
                {
                    nextToVisit.Enqueue(node.right ?? null);
                }
                else
                {
                    nextToVisit.Enqueue(node.left ?? null);
                }
            }
            return(closest);
        }
Example #34
0
        public void WideAllNodes()
        {
            BST <string> tree = new BST <string>(new BSTNode <string>(8, "Level_1 Root", null));

            tree.AddKeyValue(4, "Level_2_1 Left_Child");
            tree.AddKeyValue(12, "Level_2_2 Right_Child");
            tree.AddKeyValue(2, "Level_3_1 Left_Child");
            tree.AddKeyValue(6, "Level_3_2 Right_Child");
            tree.AddKeyValue(10, "Level_3_3 Left_Child");
            tree.AddKeyValue(14, "Level_3_4 Right_Child");
            tree.AddKeyValue(1, "Level_4_1 Left_Child");
            tree.AddKeyValue(3, "Level_4_2 Right_Child");
            tree.AddKeyValue(5, "Level_4_3 Left_Child");
            tree.AddKeyValue(7, "Level_4_4 Right_Child");
            tree.AddKeyValue(9, "Level_4_5 Left_Child");
            tree.AddKeyValue(11, "Level_4_6 Right_Child");
            tree.AddKeyValue(13, "Level_4_7 Left_Child");
            tree.AddKeyValue(15, "Level_4_8 Right_Child");

            BSTFind <string> foundRoot = tree.FindNodeByKey(8);

            tree.PrintNodes(tree.WideAllNodes());
        }
        static public int FindClosestValueInBstV4(BST tree, int target)
        {
            int FindClosest(BST node, int closest)
            {
                if (node is null)
                {
                    return(closest);
                }

                closest = Math.Abs(target - node.value) < Math.Abs(target - closest) ? node.value : closest;

                if (target > node.value)
                {
                    return(FindClosest(node.right, closest));
                }
                else
                {
                    return(FindClosest(node.left, closest));
                }
            }

            return(FindClosest(tree, tree.value));
        }
Example #36
0
    /* Reads the game score from a file. The file is predetermined. */
    internal void readScore(BST bst)
    {
        if (File.Exists(Application.dataPath + "/Records.txt"))                            //Making sure the file exists before we attempt to read it
        {
            StreamReader reader = new StreamReader(Application.dataPath + "/Records.txt"); //Opens a specific file in a stream reader
            string       line;
            string[]     split;

            while ((line = reader.ReadLine()) != null)             //the reader will return null on reaching the last line
            {
                split = line.Split(',');
                line  = "";

                for (int i = 1; i < split.Length; i++)
                {
                    line += split[i];                     //Just a precaution in case the player enters a name with commas and it gets saved. Once read, the name will have been changed as follows: "test,name" -> "testname"
                }
                bst.insert(int.Parse(split[0]), line);
            }

            reader.Close();             //Closing the stream
        }
    }
Example #37
0
        public override void Remove(K key)
        {
            // Get the hashcode (the key of the object passed in)
            int iInitialHash = HashFunction(key);

            // Current location we are looking at in the collision chain
            int iCurrentLocation = iInitialHash;

            // How many attempts were made to increment
            //int iAttempts = 1;

            BST <KeyValue <K, V> > bst = null;

            // if key exist at current location
            if (oDataArray[iCurrentLocation] != null && oDataArray[iCurrentLocation].GetType() == typeof(BST <KeyValue <K, V> >))
            {
                // planning on having this loop through every node in the bst, to try and remove the node
                bst = (BST <KeyValue <K, V> >)oDataArray[iCurrentLocation];

                //Console.WriteLine(Get(key));
                V value = Get(key);

                KeyValue <K, V> kvNew = new KeyValue <K, V>(key, value);

                IterateTree(bst);

                if (bst.Remove(kvNew) && qNodes.Count == 1)
                {
                    oDataArray[iCurrentLocation] = new Tombstone();
                }
            }
            else
            {
                // otherwise throw an exception telling the user it doesn't exist
                throw new KeyNotFoundException("Key to remove does not exist in the Hash Table");
            }
        }
Example #38
0
        public void TestSomething()
        {
            BST bst = new BST();

            bst.Insert(10);
            bst.Insert(1);
            bst.Insert(3);
            bst.Insert(15);
            bst.Insert(18);
            bst.Insert(0);

            // Tester of inorder traversal
            // bst.Inorder();

            // Tester of delete method
            //bst.Delete(10);

            // Tester of isBST check
            //Console.WriteLine(bst.IsBST());
            //Tester of kthj smallest element
            //Console.WriteLine(bst.kthSmallestElement(5).Data);

            // bst.Inorder();


            // BST bst = new BST();
            //int[] array = new int[] { 2, 3, 10, 15, 20, 28 };
            //bst.SortedArrayToBST(array);
            //bst.Preorder();
            //TraversalWithoutRecursion.InorderWithoutRecursion(bst.Root);
            //Console.WriteLine();
            //TraversalWithoutRecursion.PreorderTraversalWithoutRecusion(bst.Root);

            //Console.WriteLine();
            //TraversalWithoutRecursion.PostorderTraversalWithoutRecursion(bst.Root);
            //TestBSTMerge();
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Sort a String Array with a BST");
            BST bst = new BST();

            string[] arr = new string[] { "h", "b", "j", "e", "a", "g", "c", "f", "d", "i" };

            //find the value of the first letter and add this as the first node in the BST
            int value = arr[0][0];

            //set a default root because the add method takes in 2 nodes
            Node firstNode        = null;
            Node firstNodeOfArray = new Node(arr[0], value);

            bst.Add(firstNode, firstNodeOfArray);

            //find the rest of the values
            for (int i = 1; i < arr.Length; i++)
            {
                //add the values of each char at each index
                for (int j = 0; j < arr[i].Length; j++)
                {
                    value = arr[i][j];
                }
                //Add that string to the BST based on its ASCII total
                bst.Add(firstNodeOfArray, new Node(arr[i], value));
            }
            InOrder(firstNodeOfArray);
            MinVal(firstNodeOfArray);
            MaxVal(firstNodeOfArray);

            //print the list in order
            //foreach (string s in list)
            //{
            //	Console.WriteLine(s);
            //}
        }
Example #40
0
    static void Main(string[] args)
    {
        //Wyjasnienie dzialania

        /*
         * Zapisuje droge do pierwszego z wezlow a potem do drugiego z wezlow za pomoca tablic bool[]. Jesli te wezly maja wspolny wezel, to droga
         * dostepu do nich jest taka sama do momentu az algorytm napotka ten wspolny wezel. Z tego powodu porownuje tablice reprezentujace
         * drogi dostepu do wezlow - jesli w pewnym momencie sie roznia, to mamy sygnal, ze w wezle poprzednim do tej sytuacji mamy wspolny wezel
         *
         * Zlozonosc:
         * korzystam wylacznie z metody szukania elementu w drzewie binarnym, ktora jest pesymistycznie O(n). Porownywanie drog ma porownywalna, badzmniejsza zlozonosc, wiec CAŁOŚĆ JEST O(n)
         */


        BST <int> drzewo = new BST <int>(3);

        drzewo.Insert(2);
        drzewo.Insert(1);
        drzewo.Insert(6);
        drzewo.Insert(7);
        drzewo.Insert(5);

        /*
         *              3
         *          2           6
         *      1            5       7
         *
         *
         */

        BinaryNode <int> wspolny = drzewo.NearestCommonNode(1, 5);

        Console.WriteLine("Wspolny: {0}", wspolny.Value);

        //KONIEC KODU
        Console.ReadLine();
    }
Example #41
0
        public void ParseBSTTest()
        {
            IEnumerable <long> preOrderList = new List <long>()
            {
                7, 4, 1, -1, -1, 6, -1, -1, 13, 10, -1, -1, 15, -1, -1
            };

            var bst = BST.ParseBST(preOrderList);

            Assert.IsTrue(BST.EnsureBSTConsistency(bst.Root));

            Assert.AreEqual("7(4(1,6),13(10,15))", bst.ToString());
            var n = bst.Find(4);

            Assert.AreEqual(4, n.Key);

            n = bst.Find(5);
            Assert.AreEqual(6, n.Key);
            var nn = bst.Next(n);

            Assert.AreEqual(7, nn.Key);

            n = bst.Find(4);
            Assert.AreEqual(4, n.Key);
            nn = bst.Next(n);
            Assert.AreEqual(6, nn.Key);

            n = bst.Find(15);
            Assert.AreEqual(15, n.Key);
            nn = bst.Next(n);
            Assert.AreEqual(null, nn);

            var range = bst.RangeSearch(1, 6);

            Assert.AreEqual("1 4 6",
                            string.Join(" ", range.Select(x => x.Key)));
        }
Example #42
0
        static void BSTTest()
        {
            var bst = new BST <int>();

            bst.insert(17);
            bst.insert(25);
            bst.insert(5);
            bst.insert(8);
            bst.insert(1);
            bst.insert(15);
            bst.insert(6);
            bst.insert(11);
            bst.insert(10);
            bst.insert(26);
            bst.insert(29);

// traversals
            bst.inorder();
            bst.pre();
            bst.post();

            Console.WriteLine("Delete 25");
            bst.delete(25);
            bst.inorder();

            Console.WriteLine("Delete 17");
            bst.delete(17);
            bst.inorder();

            Console.WriteLine("Delete 8");
            bst.delete(8);
            bst.inorder();

            Console.WriteLine("Delete 1");
            bst.delete(1);
            bst.inorder();
        }
        public void BST_BulkInit_Test()
        {
            var nodeCount = 1000;

            var rnd           = new Random();
            var sortedNumbers = Enumerable.Range(1, nodeCount).ToList();

            var tree = new BST <int>(sortedNumbers);

            Assert.IsTrue(tree.Root.IsBinarySearchTree(int.MinValue, int.MaxValue));
            Assert.AreEqual(tree.Count, tree.Count());

            tree.Root.VerifyCount();

            for (int i = 0; i < nodeCount; i++)
            {
                Assert.IsTrue(tree.Root.IsBinarySearchTree(int.MinValue, int.MaxValue));
                tree.Delete(sortedNumbers[i]);

                Assert.IsTrue(tree.Count == nodeCount - 1 - i);
            }

            Assert.IsTrue(tree.Count == 0);
        }
Example #44
0
        public void PostOrderTravelsal_GivenValidTree_ExpectResult2()
        {
            //Given
            var tree = new BST {
                Root = new Node(20)
            };

            tree.Root.Left        = new Node(15);
            tree.Root.Right       = new Node(25);
            tree.Root.Left.Left   = new Node(13);
            tree.Root.Left.Right  = new Node(16);
            tree.Root.Right.Left  = new Node(22);
            tree.Root.Right.Right = new Node(45);

            var expected = new List <int> {
                13, 16, 15, 22, 45, 25, 20
            };

            //When
            var actual = Utilities.TreePostOrderTraversal(tree.Root);

            //Then
            actual.Should().BeEquivalentTo(expected);
        }
Example #45
0
        public static bool Validate(BST root)
        {
            if (root == null)
            {
                return(false);
            }
            var current = root;

            while (true)
            {
                if (current.left.value < current.right.value)
                {
                    current = current.left;
                }
                else if (current.right.value > current.left.value)
                {
                    current = current.left;
                }
                else
                {
                    return(false);
                }
            }
        }
        //n solution
        private static int FindClosestValueInBst(BST tree, int target)
        {
            int temp = Math.Abs(tree.value - target), res = tree.value;

            if (tree.left != null)
            {
                int distanceLeft = Math.Abs(target - FindClosestValueInBst(tree.left, target));
                if (distanceLeft < temp)
                {
                    temp = distanceLeft;
                    res  = FindClosestValueInBst(tree.left, target);
                }
            }
            if (tree.right != null)
            {
                int distanceRight = Math.Abs(target - FindClosestValueInBst(tree.right, target));
                if (distanceRight < temp)
                {
                    temp = distanceRight;
                    res  = FindClosestValueInBst(tree.right, target);
                }
            }
            return(res);
        }
Example #47
0
    static void Main(string[] args)
    {
        BST<int> firdtTree = new BST<int>();
            firdtTree.AddElement(1);
            firdtTree.AddElement(2);
            firdtTree.AddElement(5);
            firdtTree.AddElement(7);
            firdtTree.AddElement(9);

            BST<int> secondTree = (BST<int>)firdtTree.Clone();

            Console.WriteLine("First Tree: {0}" ,firdtTree.ToString());
            Console.WriteLine("Second Tree: {0} ",secondTree.ToString());
            Console.WriteLine("First Tree equals Second Tree: {0}",firdtTree.Equals(secondTree));

            Console.Write("Traverse with foreach: ");
            foreach (TreeNode<int> item in firdtTree)
                Console.Write(item.Value + " ");

            Console.WriteLine();

            Console.WriteLine("First Tree hash: {0}", firdtTree.GetHashCode());
            Console.WriteLine("Second Tree hash: {0}", secondTree.GetHashCode());
    }
Example #48
0
        private void ExpandHashTable()
        {
            // Create a reference to the existing HashTable
            object[] oOldArray = oDataArray;

            // Create a new array length of old array times 2
            oDataArray = new object[oDataArray.Length * 2];

            // Reset the attributes
            iCount         = 0;
            iNumCollisions = 0;

            // Loop through the existing tabel and re-hash each line
            for (int i = 0; i < oOldArray.Length; i++)
            {
                if (oOldArray[i] != null)
                {
                    // If the current value is a key-value (and not a tombstone).
                    // Use get GetType() when dealing with an instance of something
                    if (oOldArray[i].GetType() == typeof(BST <KeyValue <K, V> >))
                    {
                        // Get a reference to the current key-value
                        BST <KeyValue <K, V> > bst = (BST <KeyValue <K, V> >)oOldArray[i];

                        IterateTree(bst);

                        while (qNodes.Count > 0)
                        {
                            KeyValue <K, V> reHash = qNodes.Dequeue();

                            this.Add(reHash.Key, reHash.Value);
                        }
                    }
                }
            }
        }
Example #49
0
        public void TestBST()
        {
            BST<string, int> st = new BST<string, int>();

            int amounts = 20;
            string[] strs = new string[amounts];
            Random rand = new Random();
            for (int i = 0; i < amounts; i++)
            {
                strs[i] = Convert.ToChar(rand.Next(97, 122)).ToString();
                st.Put(strs[i], i);
            }
            StringBuilder sb0 = new StringBuilder();
            foreach (var str in strs)
                sb0.Append(str + " ");
            Debug.WriteLine(sb0.ToString());

            StringBuilder sb = new StringBuilder();
            foreach (var item in st.Keys())
                sb.Append(item + "-" + st.Get(item) + " ");
            Debug.WriteLine(sb.ToString());

            Assert.AreEqual(strs.Distinct().Count(), st.Keys().Count());
        }
Example #50
0
        public void FindEdgesTest()
        {
            int[] arr      = new int[] { 2 };
            int   distance = BST.FindEdges(arr, 2, 2);

            if (distance != 0)
            {
                Assert.Fail();
            }

            arr      = new int[] { };
            distance = BST.FindEdges(arr, 2, 2);
            if (distance != -1)
            {
                Assert.Fail("distance should = -1");
            }

            arr      = new int[] { 2, 5, 1, 6 };
            distance = BST.FindEdges(arr, 2, 7);
            if (distance != -1)
            {
                Assert.Fail("distance should = -1");
            }
        }
Example #51
0
 public bool AreSame(BST tree1, BST tree2)
 {
     return recAreSame(tree1.Root, tree2.Root);
 }
Example #52
0
        private BST CreateBstFromArray(int[] nums, int startIndex)
        {
            BST bst = new BST();
            bst.Value = nums[startIndex];

            if (startIndex >= nums.Count() - 1)
            {
                return bst;
            }

            if (bst.Value < nums[startIndex + 1])
            {
                bst.Right = CreateBstFromArray(nums, startIndex + 1);
            }
            else
            {
                bst.Left = CreateBstFromArray(nums, startIndex + 1);
            }

            return bst;
        }
 public bool IsBST(BST tree)
 {
     return recIsBST(tree.Root, int.MinValue, int.MaxValue);
 }
 public static Node<int> FindCommonAncestor(BST<int> tree, int i, int j)
 {
     return FindCommonAncestor(tree.getRoot(), i, j);
 }