using System.Collections.Generic;
public static void Main()
BinarySearchTree<int> tree = new BinarySearchTree<int>();
Console.WriteLine(tree.IsValidBinarySearchTreeRecursive(tree.root).ToString());
public class Node<T> where T : IComparable
public class BinarySearchTree<T> where T : IComparable
public BinarySearchTree()
public bool Insert(T data)
Node<T> after = this.root;
if(data.CompareTo(after.data) < 0)
else if(data.CompareTo(after.data) > 0)
Node<T> newNode = new Node<T>(data);
if(data.CompareTo(before.data) < 0)
private bool _HelperForIsValidBinarySearchTreeRecursive(Node<T> node, T lower, T upper)
Type nodeType = typeof(T);
if(val.CompareTo(lower) <= 0)
if(val.CompareTo(upper) >= 0)
if(lower != null && val.CompareTo(lower) <= 0)
if(upper != null && val.CompareTo(upper) >= 0)
if(!_HelperForIsValidBinarySearchTreeRecursive(node.right, val, upper))
if(!_HelperForIsValidBinarySearchTreeRecursive(node.left, lower, val))
public bool IsValidBinarySearchTreeRecursive(Node<T> root)
Type nodeType = typeof(T);
return _HelperForIsValidBinarySearchTreeRecursive(root, root.data, root.data);
return _HelperForIsValidBinarySearchTreeRecursive(root, default(T), default(T));
public static class StaticUtilities
private static readonly HashSet<Type> NumericTypes = new HashSet<Type>
typeof(int), typeof(double), typeof(decimal),
typeof(long), typeof(short), typeof(sbyte),
typeof(byte), typeof(ulong), typeof(ushort),
typeof(uint), typeof(float)
public static bool IsNumeric(this Type myType)
return NumericTypes.Contains(Nullable.GetUnderlyingType(myType) ?? myType);