본문 바로가기
c#/수업 내용

자료구조 이진트리(배열)

by 이지훈26 2021. 9. 29.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Helloworld1
{
    class BinaryTreeArr
    {
        public string[] arr;
        //생성자
        public BinaryTreeArr(int data)
        {
            arr = new string[data];
        }

        public void AddRoot(string data)
        {
            if(arr[0] == null)  //루트가 비어있다면
            {
                arr[0] = data;  //루트 출력
            }
            else
            {
                Console.WriteLine("");
            }
        }

        public void AddLeft(int parentIndex, string data)
        {
            if(arr[parentIndex] == null)
            {
                Console.WriteLine("");
            }
            else
            {
                arr[parentIndex * 2 + 1] = data;
            }
        }

        public void AddRight(int parentIndex, string data)
        {
            if(arr[parentIndex] == null)
            {
                Console.WriteLine("");
            }
            else
            {
                arr[parentIndex * 2 + 2] = data;
            }
        }
        public void Print()
        {
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == null)
                    Console.Write("x ");

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


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Helloworld1
{
    class App2
    {
        public App2()
        {
            var bt = new BinaryTreeArr(15);
            bt.AddRoot("F");
            bt.AddLeft(0, "B");
            bt.AddRight(0, "G");
            bt.AddRight(1, "A");
            bt.AddRight(1, "D");
            bt.AddLeft(2, "I");
            bt.AddLeft(4, "C");
            bt.AddRight(4, "E");
            bt.AddLeft(6, "H");

            bt.Print();
        }
    }
}