Saturday, 26 July 2014

Sample binary tree using C#

using System;

namespace myBtree
{
    class Program
    {
        public static void Main(string[] args)
        {
            string str = "  ";
            bTree bt = new bTree();
            bt.add(1);
            bt.add(12);
            bt.add(11);
            bt.add(165);
            bt.add(13);
            bt.add(3);
            bt.add(6);
            bt.add(9);
            bt.add(10);
            bt.add(7);
            bt.add(5);
            bt.add(15);            
            bt.add(150);
            bt.add(1800000);
            bt.add(4);
            bt.add(100);
           
            // TODO: Implement Functionality Here
           
            bt.read();
           
        //    Console.Write("\nPress any key to continue . . . ");
            Console.ReadKey(true);
        }
    }

    public class bTree
    {
        public int index = 0;
        bTree left;
        bTree right;
        int cursorPos = 1;
        public bTree()
        {
        }
       
        public void add(int value)
        {
            if(this.index > value)
            {
                if(left == null)
                {
                    left = new bTree();
                    left.index = value;
                    left.cursorPos = this.cursorPos;
                }
                else
                {
                    left.add(value);
                }
               
            }
            else if(this.index < value)
            {
                if(right == null)
                {
                    right = new bTree();
                    right.index =value;
                    right.cursorPos = value.ToString().ToCharArray().Length + this.cursorPos + 2;
                }
                else
                {
                    right.add(value);
                }
            }
        }
       

        public void read()
        {
            Console.SetCursorPosition(this.cursorPos, Console.CursorTop);
            Console.Write("{0}"this.index);
               
            if(this.right != null)
            {
                Console.Write("......");
                this.right.read();
            }
            if(this.left != null)
            {
                Console.Write("\n");
                Console.SetCursorPosition(this.cursorPos, Console.CursorTop);
                Console.Write(".\n");
                this.left.read();
            }
        }
    }
}

No comments:

Post a Comment