1.生成N 层二叉树
2.树节点值为随机值
Test:
/// <summary>
///A test for BuildRandom
///</summary>
public void BuildRandomTestHelper<T>()
{
BinTree<int> target = new BinTree<int>(); // TODO: Initialize to an appropriate value
int level = 4;
BinTree<int> actual;
actual = target.BuildRandom(level,90);
BinTree<myobj> targetb = new BinTree<myobj>();
BinTree<myobj> b;
b = targetb.BuildRandom(level, 90);
BinTree<string> targetc = new BinTree<string>();
BinTree<string> c;
c = targetc.BuildRandom(level, 90);
}
Code :
public class BinTree<T>
{
public int MaxRandomValue = 1000;
public BinTreeNode<T> Root;
/// <summary>
/// Generate a binarytree.
/// 1.level is specified level
/// 2.value is random value
/// </summary>
/// <param name="level">level >=1</param>
/// <param name="possibility">0-100</param>
/// <see cref=""/>
/// <seealso cref=""/>
/// <returns></returns>
public BinTree<T> BuildRandom(int level, double possibility)
{
BinTree<T> tree = new BinTree<T>();
Queue<BinTreeNode<T>> que = new Queue<BinTreeNode<T>>();
Random ValueRand = new Random();
if (typeof(T) == typeof(Int32)
|| typeof(T) == typeof(UInt32)
|| typeof(T) == typeof(UInt64)
|| typeof(T) == typeof(Int64)
|| typeof(T) == typeof(double)
|| typeof(T) == typeof(Int16)
|| typeof(T) == typeof(UInt16)
|| typeof(T) == typeof(decimal)
|| typeof(T) == typeof(string)
)
{
if (level > 0)
{
tree.Root = new BinTreeNode<T>();
object val = ValueRand.Next(MaxRandomValue);
tree.Root.Value = (T)Convert.ChangeType(val, typeof(T));
que.Enqueue(tree.Root);
int preCount = que.Count;
for (int i = 0; i < level - 1; i++)
{
for (int j = 0; j < preCount; j++)
{
BinTreeNode<T> parent = que.Dequeue();
bool hasNode = (int)(ValueRand.NextDouble() * 100) < possibility;
if (hasNode)
{
BinTreeNode<T> newNode = new BinTreeNode<T>();
val = ValueRand.Next(MaxRandomValue);
newNode.Value = (T)Convert.ChangeType(val, typeof(T));
parent.LeftChild = newNode;
que.Enqueue(newNode);
}
if (!hasNode)
{
hasNode = true;
}
else
{
hasNode = (int)(ValueRand.NextDouble() * 100) < possibility;
}
if (hasNode)
{
BinTreeNode<T> newNode = new BinTreeNode<T>();
val = ValueRand.Next(MaxRandomValue);
newNode.Value = (T)Convert.ChangeType(val, typeof(T));
parent.RightChild = newNode;
que.Enqueue(newNode);
}
}
preCount = que.Count;
}
}
}
return tree;
}
}