0401 배열을 사용해 이진트리 구현하기 복습

2021. 4. 1. 10:55C#/자료구조

public class BinaryTreeUsingArray
    {
        private string[] arr;
        public string Root
        {
            get
            {
                return this.arr[0];
            }
            set
            {
                this.arr[0] = value;
            }
        }

        public BinaryTreeUsingArray(int capacity) 
        {
            this.arr = new string[capacity]; 
        }
        public void AddLeft(int parentIndex,string data) 
        {
            var leftIndex = (parentIndex * 2) + 1;
            this.arr[leftIndex] = data;
        }
        public void AddRight(int parentIndex,string data) 
        {
            var rightIndex = (parentIndex * 2) + 2;
            this.arr[rightIndex] = data;
        }
        public string GetPrarent(int childIndex) 
        {
            var parentIndex = (childIndex - 1) / 2;
            return this.arr[parentIndex];
        }
        public void Print() 
        {
            for (int i = 0; i < this.arr.Length; i++) 
            {
                var element = this.arr[i];
                if (element == null)
                {
                    Console.WriteLine("-");
                }
                else 
                {
                    Console.WriteLine("{0}", this.arr[i]);
                }
            }
        }
    }
public class App
    {
        public App() 
        {
            BinaryTree tree = new BinaryTree("A");
            tree.root.left = new BinaryTreeNode("B");
            tree.root.right = new BinaryTreeNode("C");
            tree.root.left.left = new BinaryTreeNode("D");

            tree.PrintPreorderTraversal();
        }
    }