Rychle vytvořit binární strom v jazyce C #

hlasů
1

Kdykoliv se snažíme udělat malý problém týkající se binárních stromů trvá věky psát základní kód naplnit dostatečně velký binární strom. Chci mít malé kód rychle postavit binární vyhledávací strom inicializován s náhodnými hodnotami.

Položena 14/07/2011 v 00:10
zdroj uživatelem
V jiných jazycích...                            


1 odpovědí

hlasů
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();
    }

}

S pozdravem, Sriwantha Sri Aravinda

Odpovězeno 14/07/2011 v 00:12
zdroj uživatelem

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more