示例#1
0
        /// <summary>
        /// Private helper method for Inorder Searcher.
        /// </summary>
        private static bool InOrderSearcher <T>(BSTNode <T> BinaryTreeRoot, T Value, bool IsBinarySearchTree = false) where T : IComparable <T>
        {
            var current  = BinaryTreeRoot.Value;
            var hasLeft  = BinaryTreeRoot.HasLeftChild;
            var hasRight = BinaryTreeRoot.HasRightChild;

            if (IsBinarySearchTree == true)
            {
                if (hasLeft && current.IsGreaterThan(Value))
                {
                    return(BinaryTreeRecursiveWalker.InOrderSearcher <T>(BinaryTreeRoot.LeftChild, Value));
                }

                if (current.IsEqualTo(Value))
                {
                    return(true);
                }

                if (hasRight && current.IsLessThan(Value))
                {
                    return(BinaryTreeRecursiveWalker.InOrderSearcher <T>(BinaryTreeRoot.RightChild, Value));
                }
            }
            else
            {
                if (hasLeft && InOrderSearcher <T>(BinaryTreeRoot.LeftChild, Value) == true)
                {
                    return(true);
                }

                if (current.IsEqualTo(Value))
                {
                    return(true);
                }

                if (hasRight && InOrderSearcher <T>(BinaryTreeRoot.RightChild, Value) == true)
                {
                    return(true);
                }
            }

            return(false);
        }
示例#2
0
        /// <summary>
        /// Search the tree for the specified value.
        /// By default this method traverses the tree in inorder fashion.
        /// </summary>
        public static bool BinarySearch <T>(BSTNode <T> BinaryTreeRoot, T Value, TraversalMode Mode = TraversalMode.InOrder) where T : IComparable <T>
        {
            if (BinaryTreeRoot == null)
            {
                throw new ArgumentNullException("Tree root cannot be null.");
            }

            // Traverse
            // Traverse
            switch (Mode)
            {
            case TraversalMode.PreOrder:
                return(BinaryTreeRecursiveWalker.PreOrderSearcher(BinaryTreeRoot, Value, IsBinarySearchTree: true));

            case TraversalMode.InOrder:
                return(BinaryTreeRecursiveWalker.InOrderSearcher(BinaryTreeRoot, Value, IsBinarySearchTree: true));

            case TraversalMode.PostOrder:
                return(BinaryTreeRecursiveWalker.PostOrderSearcher(BinaryTreeRoot, Value, IsBinarySearchTree: true));

            default:
                return(BinaryTreeRecursiveWalker.InOrderSearcher(BinaryTreeRoot, Value, IsBinarySearchTree: true));
            }
        }