C#/수업 내용

[C#] 배열 Binary Tree

JSH1 2021. 9. 29. 12:43

    class App
    {
        public App()
        {
            var bt = new BinaryTree(15);

            bt.AddRoot("F");
            bt.AddLeft(0, "B");
            bt.AddRight(0, "G");
            bt.AddLeft(1, "A");
            bt.AddRight(1, "D");
            bt.AddRight(2, "I");
            bt.AddLeft(4, "C");
            bt.AddRight(4, "E");
            bt.AddLeft(6, "H");

            bt.Print();
        }
    }
    class BinaryTree
    {
        public string[] root;

        public BinaryTree(int data)
        {
            root = new string[data];
        }

        public void AddRoot(string data)
        {
            if (root[0] == null) root[0] = data;
        }

        public void AddLeft(int parent, string data)
        {
            root[parent * 2 + 1] = data;
        }

        public void AddRight(int parent, string data)
        {
            root[parent * 2 + 2] = data;
        }

        public void Print()
        {
            for (int i = 0; i < root.Length; i++)
            {
                if (root[i] == null)
                    Console.Write("x ");

                else
                    Console.Write(root[i] + " ");
            }
        }
    }