コード例 #1
0
        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 });
        }
コード例 #2
0
ファイル: BST.cs プロジェクト: TerrorEdje/Algoritmiek
 public void insertAVL(int number)
 {
     if (root == null)
     {
         root = new BSTNode(number);
     }
     else
     {
         root = root.insertAVL(number);
     }
 }
コード例 #3
0
ファイル: P15_5.cs プロジェクト: slao-learn/epi
 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);
 }
コード例 #4
0
ファイル: P15_4.cs プロジェクト: slao-learn/epi
        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;
        }
コード例 #5
0
ファイル: P15_5.cs プロジェクト: slao-learn/epi
 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;
 }
コード例 #6
0
 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);
     }
 }
コード例 #7
0
        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);
            }
        }
コード例 #8
0
ファイル: P15_3.cs プロジェクト: slao-learn/epi
 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;
 }
コード例 #9
0
ファイル: BST.cs プロジェクト: cabhishek/theinterview
        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;
        }
コード例 #10
0
ファイル: P15_3.cs プロジェクト: slao-learn/epi
 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);
 }
コード例 #11
0
ファイル: P15_4.cs プロジェクト: slao-learn/epi
    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] + " ");
        }
    }
コード例 #12
0
        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");
        }
コード例 #13
0
        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!");
        }
コード例 #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));
    }
コード例 #15
0
ファイル: BST.cs プロジェクト: eruandou/ZambranoPrograII
 public void InitializeTree()
 {
     root = null;
 }
コード例 #16
0
ファイル: P15_3.cs プロジェクト: slao-learn/epi
 public BSTNode(int data, int lData, int rData)
     : this(data, null, null)
 {
     this.left = new BSTNode(lData);
     this.right = new BSTNode(rData);
 }
コード例 #17
0
 public PolandReview(BSTNode reviewData) => Review = new Review(reviewData);
コード例 #18
0
ファイル: P15_4.cs プロジェクト: slao-learn/epi
 public BSTNode(int data, int lData, int rData) : this(data, null, null)
 {
     this.left  = new BSTNode(lData);
     this.right = new BSTNode(rData);
 }
コード例 #19
0
ファイル: Program.cs プロジェクト: maxflamer/Practice
 public BSTNode(int d)
 {
     data  = d;
     left  = null;
     right = null;
 }
コード例 #20
0
 public AbstractReview(BSTNode node)
 {
     review = node;
 }
コード例 #21
0
 public ItalyReview(BSTNode node) : base(node)
 {
 }
コード例 #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;
 }
コード例 #23
0
        /// <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);
        }
コード例 #24
0
 public FranceReview(BSTNode reviewData) => Review = new Review(reviewData);
コード例 #25
0
 /// <summary>
 /// Clears all elements from the BST&lt;T&gt;.
 /// </summary>
 public void Clear()
 {
     mRoot  = null;
     mCount = 0;
 }
コード例 #26
0
ファイル: BST.cs プロジェクト: cabhishek/theinterview
 public void Insert(int item)
 {
     nodeCount++;
     root = recInsert(item, root);
 }
コード例 #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;
 }
コード例 #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--;
         }
コード例 #29
0
ファイル: P15_4.cs プロジェクト: slao-learn/epi
 public BSTNode(int data, BSTNode left, BSTNode right)
 {
     this.data  = data;
     this.left  = left;
     this.right = right;
 }
コード例 #30
0
 public BinarySearchTree(int value)
 {
     root = new BSTNode(value);
 }
コード例 #31
0
ファイル: P15_3.cs プロジェクト: slao-learn/epi
 public BSTNode(int data, BSTNode left, BSTNode right)
 {
     this.data = data;
     this.left = left;
     this.right = right;
 }
コード例 #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);
    }
コード例 #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);
 }
コード例 #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;
 }
コード例 #35
0
ファイル: BST.cs プロジェクト: cabhishek/theinterview
 public BST()
 {
     root = null;
     nodeCount = 0;
 }
コード例 #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));
 }
コード例 #37
0
 public BSTNode(int value)
 {
     this.value = value;
     left       = right = null;
 }
コード例 #38
0
 public virtual void Clear()
 {
     _root = null;
     _count = 0;
 }