Ogni volta che cerchiamo di fare un piccolo problema relativo agli alberi binari che ci vuole molto tempo per scrivere il codice di base per popolare un grande albero binario abbastanza. Voglio avere un piccolo codice per costruire rapidamente un albero binario di ricerca inizializzato con valori casuali.
creare rapidamente un albero binario in C #
voti
1
È pubblicato 14/07/2011 alle 00:10 2011-07-14 00:10
fonte dall'utente Sriwantha Attanayake
In altre lingue...
fonte dall'utente Sriwantha Attanayake
In altre lingue...
1 risposte
voti 1
1
static void Main(string[] args)
{
int numberOfNodes = 10;
Random rand = new Random();
int[] randomValues = Enumerable.Repeat(0, numberOfNodes).Select(i => rand.Next(0, 100)).ToArray();
//sort the array
int[] binaryTreeValues = (from x in randomValues orderby x select x).ToArray();
BNode root = null;
Construct(ref root, ref binaryTreeValues, 0, binaryTreeValues.Length - 1);
}
public static void Construct(ref BNode root, ref int[] array, int start, int end)
{
if (start > end)
{
root = null;
}
else if (start == end)
{
root = new BNode(array[start]);
}
else
{
int split = (start + end) / 2;
root = new BNode(array[split]);
Construct(ref root.Left, ref array, start, split - 1);
Construct(ref root.Right, ref array, split + 1, end);
}
}
public class BNode
{
public int ID;
public int Level;
public BNode Left;
public BNode Right;
public BNode(int ID)
{
this.ID = ID;
}
public override string ToString()
{
return this.ID.ToString();
}
}
Saluti, Sriwantha Sri Aravinda