스토리지

[3.31] Binary Tree 연습 1 (Array) 본문

Unity/자료구조

[3.31] Binary Tree 연습 1 (Array)

ljw4104 2021. 3. 31. 15:49

Tree를 이루는 Array의 형태 ( 1부터 시작하는 Index )

0 1 2 3 4 5 6 7
null A B C D null null G

( ∵ 배열을 1부터 시작하는 이유는 인덱스가 잘 보이고 계산하기 편하다... )

 

using System;

namespace Study02
{
    public class BinaryTree
    {
        private string[] arr;
        public BinaryTree(int capacity = 8)
        {
            this.arr = new string[capacity];
        }

        public void SetRoot(string data)
        {
            this.arr[1] = data;
        }

        public string GetRoot()
        {
            return this.arr[1];
        }

        public void SetLeft(int parentIndex, string data)
        {
            if(this.arr[parentIndex] == null || parentIndex * 2 >= this.arr.Length) 
                return;
            this.arr[parentIndex * 2] = data;
        }

        public string GetLeft(int parentIndex)
        {
            return this.arr[parentIndex * 2];
        }

        public void SetRight(int parentIndex, string data)
        {
            if (this.arr[parentIndex] == null || parentIndex * 2 + 1 >= this.arr.Length)
                return;
            arr[parentIndex * 2 + 1] = data;
        }

        public string GetRight(int parentIndex)
        {
            return this.arr[parentIndex * 2 + 1];
        }

        public string GetParent(int childIndex)
        {
            return this.arr[childIndex / 2];
        }

        public void Print()
        {
            for(int i = 1; i < this.arr.Length; i++)
            {
                Console.Write("{0} ", this.arr[i] ?? "-");
            }
            Console.WriteLine();
        }
    }
}
using System;

namespace Study02
{
    public class App
    {
        public App()
        {
            BinaryTree tree = new BinaryTree();
            tree.SetRoot("A");

            tree.SetLeft(1, "B");
            tree.SetRight(1, "C");

            tree.SetLeft(2, "D");

            tree.SetRight(3, "G");

            tree.Print();
        }
    }
}

 

* ?? 연산자

object obj = expression1 ?? expression2

- expression1 값(or 참조값)이 null이면 expression2를 대입한다.

'Unity > 자료구조' 카테고리의 다른 글

[4.1] Binary Tree Traversal 복습  (0) 2021.04.01
[3.31] Binary Tree Preorder 연습  (0) 2021.03.31
[3.31] 이진 트리  (0) 2021.03.31
[3.31] LCRSTree 복습  (0) 2021.03.31
[3.30] 트리 연습 1  (0) 2021.03.30
Comments