public static void DoTest()
        {
            // Construct a Simple Binary Search Tree
            var root = new BSTNode<int>(10) {
                LeftChild = new BSTNode<int>(5) {
                    LeftChild = new BSTNode<int>(3),
                    RightChild = new BSTNode<int>(7)
                },
                RightChild = new BSTNode<int>(15) {
                    LeftChild = new BSTNode<int>(13),
                    RightChild = new BSTNode<int>(17)
                }
            };

            // Test Tree Traversal methods
            BinaryTreeRecursiveWalkerTests.Test_PreOrder_Traversal(root);
            BinaryTreeRecursiveWalkerTests.Test_InOrder_Traversal(root);
            BinaryTreeRecursiveWalkerTests.Test_PostOrder_Traversal(root);

            // Test Contains method
            BinaryTreeRecursiveWalkerTests.Test_Contain_Returns_True(root, new int[] { 10, 5, 3, 7, 15, 13, 17 });
            BinaryTreeRecursiveWalkerTests.Test_Contain_Returns_False(root, new int[] { 0, 20, 30, 40, 50 });

            // Test Binary Search method
            BinaryTreeRecursiveWalkerTests.Test_Binary_Search_Returns_True(root, new int [] { 10, 5, 3, 7, 15, 13, 17 });
            BinaryTreeRecursiveWalkerTests.Test_Binary_Search_Returns_False(root, new int[] { 0, 20, 30, 40, 50 });
        }
Beispiel #2
0
 public void insertAVL(int number)
 {
     if (root == null)
     {
         root = new BSTNode(number);
     }
     else
     {
         root = root.insertAVL(number);
     }
 }
Beispiel #3
0
 public static void RunTests()
 {
     BSTNode a = new BSTNode(3, 2, 5);
     BSTNode b = new BSTNode(17, new BSTNode(13), null);
     BSTNode t = new BSTNode(19,
         new BSTNode(7, a, new BSTNode(11, null, b)),
         new BSTNode(43,
             new BSTNode(23, null, new BSTNode(37, new BSTNode(29, null, new BSTNode(31)), new BSTNode(41))),
             new BSTNode(47, null, new BSTNode(53))
         )
     );
     Console.WriteLine(GetLCA(t, a, b).data);
 }
Beispiel #4
0
        public static List<int> FindKLargestKeys(BSTNode n, int k)
        {
            if (n == null)
                return new List<int>();

            List<int> kLargest = FindKLargestKeys(n.right, k);
            if (kLargest.Count < k)
            {
                kLargest.Add(n.data);
                if (kLargest.Count < k)
                    kLargest.AddRange(FindKLargestKeys(n.left, k - kLargest.Count));
            }
            return kLargest;
        }
Beispiel #5
0
 public static BSTNode GetLCA(BSTNode root, BSTNode a, BSTNode b)
 {
     int min = Math.Min(a.data, b.data);
     int max = Math.Max(a.data, b.data);
     BSTNode lca = root;
     while (lca.data < min || lca.data > max)
     {
         while (lca.data > max)
             lca = lca.left;
         while (lca.data < min)
             lca = lca.right;
     }
     return lca;
 }
 private static bool recHasSumPath(BSTNode node, int sum)
 {
     //base case
     if (node == null)
         //core logic
         return sum == 0;
     else
     {
         //reduce problem set
         int subSum = sum - node.data;
         //sum == 0 could be in left OR right sub tree.
         return recHasSumPath(node.left, subSum) || recHasSumPath(node.right, subSum);
     }
 }
        private static void recPrintPaths(BSTNode node, int[] paths, int len)
        {
            if (node == null) return;

            paths[len] = node.data;
            len++;

            if (node.left == null && node.right == null)
                printArray(paths, len);
            else
            {
                recPrintPaths(node.left, paths, len);
                recPrintPaths(node.right, paths, len);
            }
        }
Beispiel #8
0
 public static BSTNode FindFirstGreaterThanK(BSTNode n, int k)
 {
     BSTNode result = null;
     while (n != null)
     {
         if (n.data > k)
         {
             if (result == null || n.data < result.data)
                 result = n;
             n = n.left;
         } else
         {
             n = n.right;
         }
     }
     return result;
 }
Beispiel #9
0
        private static BSTNode recInsert(int item, BSTNode node)
        {
            if (node == null)
            {
                node = new BSTNode {left = null, right = null, data = item};
            }
            else if (item.CompareTo(node.data) < 0)
            {
                node.left = recInsert(item, node.left); //insert at the left
            }
            else
            {
                node.right = recInsert(item, node.right); // insert at right
            }

            return node;
        }
Beispiel #10
0
 public static void RunTests()
 {
     BSTNode t = new BSTNode(19,
                                 new BSTNode(7, new BSTNode(3, 2, 5), new BSTNode(11, null, new BSTNode(17, new BSTNode(13), null))),
                                 new BSTNode(43,
                                     new BSTNode(23, null, new BSTNode(37, new BSTNode(29, null, new BSTNode(31)), new BSTNode(41))),
                                     new BSTNode(47, null, new BSTNode(53))
                                 )
                             );
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 23).data);
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 18).data);
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 55) == null);
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 52).data);
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 16).data);
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 17).data);
     Console.WriteLine(BSTNode.FindFirstGreaterThanK(t, 1).data);
 }
Beispiel #11
0
    public static void RunTests()
    {
        BSTNode t = new BSTNode(19,
                                new BSTNode(7, new BSTNode(3, 2, 5), new BSTNode(11, null, new BSTNode(17, new BSTNode(13), null))),
                                new BSTNode(43,
                    new BSTNode(23, null, new BSTNode(37, new BSTNode(29, null, new BSTNode(31)), new BSTNode(41))),
                    new BSTNode(47, null, new BSTNode(53))));
        List<int> largest = BSTNode.FindKLargestKeys(t, 3);
        for (int i = 0; i < largest.Count; ++i)
        {
            Console.Write(largest[i] + " ");
        }
        Console.WriteLine();

        largest = BSTNode.FindKLargestKeys(t, 7);
        for (int i = 0; i < largest.Count; ++i)
        {
            Console.Write(largest[i] + " ");
        }
    }
        private static void Test_Binary_Search_Returns_False(BSTNode<int> root, int[] values)
        {
            var preOrder = BinaryTreeRecursiveWalker.TraversalMode.PreOrder;
            var inOrder = BinaryTreeRecursiveWalker.TraversalMode.InOrder;
            var postOrder = BinaryTreeRecursiveWalker.TraversalMode.PostOrder;

            foreach (var value in values)
                Debug.Assert(
                    false == BinaryTreeRecursiveWalker.BinarySearch(root, value, preOrder),
                    "Wrong boolean returned, expected False from Contains");

            foreach (var value in values)
                Debug.Assert(
                    false == BinaryTreeRecursiveWalker.BinarySearch(root, value, inOrder),
                    "Wrong boolean returned, expected False from Contains");

            foreach (var value in values)
                Debug.Assert(
                    false == BinaryTreeRecursiveWalker.BinarySearch(root, value, postOrder),
                    "Wrong boolean returned, expected False from Contains");
        }
        private static void Test_PreOrder_Traversal(BSTNode<int> root)
        {
            var preOrder = BinaryTreeRecursiveWalker.TraversalMode.PreOrder;

            // List to contain items
            List<int> list = new List<int>();

            // ForEach Action
            var addToList = new Action<int>(list.Add);

            // Assert the fact that adding items PRE-ORDER will result in [3, 5, 7, 10, 13, 15, 17]
            BinaryTreeRecursiveWalker.ForEach(root, addToList, preOrder);

            Debug.Assert(
                list.ToArray() == new int[] { 3, 5, 7, 10, 13, 15 },
                "Wrong traversal, expected InOrder enumeration of tree!");
        }
Beispiel #14
0
    /// <summary>
    /// Removes the first occurrence of the specified element from the BST&lt;T&gt;.
    /// </summary>
    /// <param name="item">The element to remove from the collection.</param>
    /// <returns>True if the element was found, otherwise false.</returns>
    public bool Remove(T item)
    {
        BSTNode node = Find(item);

        return(Remove(node));
    }
Beispiel #15
0
 public void InitializeTree()
 {
     root = null;
 }
Beispiel #16
0
 public BSTNode(int data, int lData, int rData)
     : this(data, null, null)
 {
     this.left = new BSTNode(lData);
     this.right = new BSTNode(rData);
 }
Beispiel #17
0
 public PolandReview(BSTNode reviewData) => Review = new Review(reviewData);
Beispiel #18
0
 public BSTNode(int data, int lData, int rData) : this(data, null, null)
 {
     this.left  = new BSTNode(lData);
     this.right = new BSTNode(rData);
 }
Beispiel #19
0
 public BSTNode(int d)
 {
     data  = d;
     left  = null;
     right = null;
 }
Beispiel #20
0
 public AbstractReview(BSTNode node)
 {
     review = node;
 }
 public ItalyReview(BSTNode node) : base(node)
 {
 }
Beispiel #22
0
 public BSTNode(T value, int subTreeSize, BSTNode <T> parent, BSTNode <T> left, BSTNode <T> right)
 {
     Value      = value;
     Parent     = parent;
     LeftChild  = left;
     RightChild = right;
 }
        /// <summary>
        /// /// Recusively draws the tree starting from node.
        /// To construct a full tree representation concatenate the returned list of strings by '\n'.
        ///
        /// Example:
        /// int position, width;
        /// var fullTree = String.Join("\n", _recursivelyDrawTree(this.Root, out position, out width));
        ///
        /// Algorithm developed by MIT OCW.
        /// http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/readings/binary-search-trees/bstsize_r.py
        /// </summary>
        /// <param name="node"></param>
        /// <param name="positionOutput"></param>
        /// <param name="widthOutput"></param>
        /// <returns>List of tree levels as strings.</returns>
        ///


        // For AVLTree
        private static List <string> _recursivelyDrawTreeAVL <T>
            (BSTNode <T> node, out int positionOutput, out int widthOutput)
            where T : IComparable <T>
        {
            widthOutput    = 0;
            positionOutput = 0;

            if (node == null)
            {
                return(new List <string>());
            }

            //
            // Variables
            int leftPosition, rightPosition, leftWidth, rightWidth;

            //
            // Start drawing
            var nodeLabel = Convert.ToString(node.Value);

            // Visit the left child
            List <string> leftLines = _recursivelyDrawTreeAVL(node.LeftChild, out leftPosition, out leftWidth);

            // Visit the right child
            List <string> rightLines = _recursivelyDrawTreeAVL(node.RightChild, out rightPosition, out rightWidth);

            // Calculate pads
            int middle       = Math.Max(Math.Max(2, nodeLabel.Length), (rightPosition + leftWidth - leftPosition + 1)) + 4;
            int position_out = (leftPosition + middle / 2) + 1;
            int width_out    = (leftPosition + middle + rightWidth - rightPosition) + 4;

            while (leftLines.Count < rightLines.Count)
            {
                leftLines.Add(new String(' ', leftWidth));
            }

            while (rightLines.Count < leftLines.Count)
            {
                rightLines.Add(new String(' ', rightWidth));
            }

            if ((middle - nodeLabel.Length % 2 == 1) && (nodeLabel.Length < middle) && (node.Parent != null && node.IsLeftChild))
            {
                nodeLabel += ".";
            }

            // Format the node's label
            nodeLabel = nodeLabel.PadCenter(middle, '.');

            var nodeLabelChars = nodeLabel.ToCharArray();

            if (nodeLabelChars[0] == '.')
            {
                nodeLabelChars[0] = ' ';
            }

            if (nodeLabelChars[nodeLabelChars.Length - 1] == '.')
            {
                nodeLabelChars[nodeLabelChars.Length - 1] = ' ';
            }

            nodeLabel = String.Join("", nodeLabelChars);

            //
            // Construct the list of lines.
            string leftBranch  = node.HasLeftChild ? "/ " : " ";
            string rightBranch = node.HasRightChild ? " \\" : "  ";

            List <string> listOfLines = new List <string>()
            {
                // 0
                (new String(' ', leftPosition)) + nodeLabel + (new String(' ', (rightWidth - rightPosition))),

                // 1
                (new String(' ', leftPosition)) + leftBranch + (new String(' ', (middle - 2))) + rightBranch + (new String(' ', (rightWidth - rightPosition)))
            };

            //
            // Add the right lines and left lines to the final list of lines.
            listOfLines.AddRange(leftLines.Zip(rightLines, (leftLine, rightLine) =>
                                               leftLine + (new String(' ', (width_out - leftWidth - rightWidth))) + rightLine));

            //
            // Return
            widthOutput    = width_out;
            positionOutput = position_out;
            return(listOfLines);
        }
Beispiel #24
0
 public FranceReview(BSTNode reviewData) => Review = new Review(reviewData);
Beispiel #25
0
 /// <summary>
 /// Clears all elements from the BST&lt;T&gt;.
 /// </summary>
 public void Clear()
 {
     mRoot  = null;
     mCount = 0;
 }
Beispiel #26
0
 public void Insert(int item)
 {
     nodeCount++;
     root = recInsert(item, root);
 }
Beispiel #27
0
 /// <summary>
 /// Initialises a new instance of the BST&lt;T&gt; class.
 /// </summary>
 public BST()
 {
     mCount    = 0;
     mComparer = Comparer <T> .Default;
     mRoot     = null;
 }
Beispiel #28
0
         public virtual void Delete(T value)
         {
 
             BSTNode<T> current = this._root;
             BSTNode<T> parent = null;
 
             int result = current.Value.CompareTo(value);
 
             while (result != 0 && current != null)
             {
                 if (result > 0)
                 {
                     parent = current;
                     current = current.Left;
                 }
                 else if (result < 0)
                 {
                     parent = current;
                     current = current.Right;
                 }
 
                 result = current.Value.CompareTo(value);
             }
 
             if (current == null)
                 throw new ArgumentException("Cannot find item to delete.");
 
             
 
             if (current.Right == null)
             {
                 if (parent == null)
                     this._root = current.Left;
                 else
                 {
                     result = parent.Value.CompareTo(current.Value);
                     if (result > 0)
                     {
                         parent.Left = current.Left;
                     }
                     else if (result < 0)
                     {
                         parent.Right = current.Left;
                     }
                 }
             }
             else if (current.Right.Left == null)
             {
                 if (parent == null)
                     this._root = current.Right;
                 else
                 {
                     result = parent.Value.CompareTo(current.Value);
                     if (result > 0)
                     {
                         parent.Left = current.Right;
                     }
                     else if (result < 0)
                     {
                         parent.Right = current.Right;
                     }
                 }
             }
             else
             {
 
                 BSTNode<T> furthestLeft = current.Right.Left;
                 BSTNode<T> furthestLeftParent = current.Right;
 
                 while (furthestLeft.Left != null)
                 {
                     furthestLeftParent = furthestLeft;
                     furthestLeft = furthestLeft.Left;
                 }
 
                 furthestLeftParent.Left = furthestLeft.Right;
 
                 furthestLeft.Left = current.Left;
                 furthestLeft.Right = current.Right;
 
                 if (parent != null)
                 {
                     result = parent.Value.CompareTo(current.Value);
                     if (result > 0)
                     {
                         parent.Left = furthestLeft;
                     }
                     else if (result < 0)
                     {
                         parent.Right = furthestLeft;
                     }
                 }
                 else
                 {
                     this._root = furthestLeft;
                 }
             }
 
             this._count--;
         }
Beispiel #29
0
 public BSTNode(int data, BSTNode left, BSTNode right)
 {
     this.data  = data;
     this.left  = left;
     this.right = right;
 }
Beispiel #30
0
 public BinarySearchTree(int value)
 {
     root = new BSTNode(value);
 }
Beispiel #31
0
 public BSTNode(int data, BSTNode left, BSTNode right)
 {
     this.data = data;
     this.left = left;
     this.right = right;
 }
Beispiel #32
0
    bool Remove(BSTNode node)
    {
        if (node != null)
        {
            BSTNode successor;

            if ((node.LesserChild == null) && (node.GreaterChild == null))
            {
                // no children, no successor
                successor = null;
            }
            else if (node.GreaterChild == null)
            {
                successor = node.LesserChild;
            }
            else if (node.LesserChild == null)
            {
                successor = node.GreaterChild;
            }
            else
            {
                // successor is the leftmost node on the right branch
                successor = node.GreaterChild;
                while (successor.LesserChild != null)
                {
                    successor = successor.LesserChild;
                }

                // swap value with successor, then delete successor
                node.Value = successor.Value;
                return(Remove(successor));
            }

            if (node.Parent != null)
            {
                // deleted node's parent now points to the successor
                if (node.Parent.GreaterChild == node)
                {
                    node.Parent.GreaterChild = successor;
                }
                if (node.Parent.LesserChild == node)
                {
                    node.Parent.LesserChild = successor;
                }
            }

            // successor's new parent is the deleted node's parent
            if (successor != null)
            {
                successor.Parent = node.Parent;
            }

            // successor becomes the new root
            if (node == mRoot)
            {
                mRoot = successor;
            }

            mCount--;
            return(true);
        }

        return(false);
    }
Beispiel #33
0
 public static bool IsLessThan <T>(this BSTNode <T> first, BSTNode <T> second) where T : IComparable <T>
 {
     return(HandleNullCases(first, second) && first.Value.CompareTo(second.Value) < 0);
 }
Beispiel #34
0
 /// <summary>
 /// Initialises a new instance of the BST&lt;T&gt;.BSTNode class, wrapping the specified element.
 /// </summary>
 /// <param name="value"></param>
 public BSTNode(T value)
 {
     mValue  = value;
     mParent = mGreaterChild = mLesserChild = null;
 }
Beispiel #35
0
 public BST()
 {
     root = null;
     nodeCount = 0;
 }
Beispiel #36
0
 public static bool IsGreaterThanOrEqualTo <T>(this BSTNode <T> first, BSTNode <T> second) where T : IComparable <T>
 {
     return(first.IsEqualTo(second) || first.IsGreaterThan(second));
 }
Beispiel #37
0
 public BSTNode(int value)
 {
     this.value = value;
     left       = right = null;
 }
Beispiel #38
0
 public virtual void Clear()
 {
     _root = null;
     _count = 0;
 }