/// <summary> /// Private helper method for Inorder Searcher. /// </summary> private static bool PostOrderSearcher <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.PostOrderSearcher <T>(BinaryTreeRoot.LeftChild, Value)); } if (hasRight && current.IsLessThan(Value)) { return(BinaryTreeRecursiveWalker.PostOrderSearcher <T>(BinaryTreeRoot.RightChild, Value)); } if (current.IsEqualTo(Value)) { return(true); } } else { if (hasLeft && PostOrderSearcher <T>(BinaryTreeRoot.LeftChild, Value) == true) { return(true); } if (hasRight && PostOrderSearcher <T>(BinaryTreeRoot.RightChild, Value) == true) { return(true); } if (current.IsEqualTo(Value)) { return(true); } } return(false); }
/// <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)); } }