Unity/자료구조

[3.31] LCRSTree 복습

ljw4104 2021. 3. 31. 11:32
using System;
using System.Collections.Generic;

namespace Study02
{
    public class LCRSTree
    {
        public LCRSNode root;
        public LCRSTree(string data)
        {
            this.root = new LCRSNode(data);
        }

        public LCRSNode AddChild(LCRSNode parent, string data)
        {
            LCRSNode child = new LCRSNode(data);
            if (parent.left == null)
            {
                parent.left = child;
            }
            else
            {
                var temp = parent.left;
                while (temp.right != null)
                {
                    temp = temp.right;
                }
                temp.right = child;
            }
            return child;
        }

        public LCRSNode AddSibling(LCRSNode node, string data)
        {
            LCRSNode sibling = new LCRSNode(data);
            while (node.right != null)
            {
                node = node.right;
            }
            node.right = sibling;
            return sibling;
        }

        //BFS 알고리즘
        public void PrintLevelOrder()
        {
            Queue<LCRSNode> queue = new Queue<LCRSNode>();
            queue.Enqueue(this.root);
            while (queue.Count > 0)
            {
                var temp = queue.Dequeue();
                while (temp != null)
                {
                    if (temp.left != null)
                    {
                        queue.Enqueue(temp.left);
                    }
                    Console.Write("{0} ", temp.data);
                    temp = temp.right;
                }
                Console.WriteLine();
            }
        }

        public void PrintIndentTree()
        {
            PrintIndentImpl(this.root, 1);
        }

        //DFS 알고리즘의 변형형태
        private void PrintIndentImpl(LCRSNode node, int indent)
        {
            if (node == null)
            {
                return;
            }
            string pad = " ".PadLeft(indent);
            Console.WriteLine("{0}{1}", pad, node.data);

            PrintIndentImpl(node.left, indent + 1);
            PrintIndentImpl(node.right, indent);
        }
    }
}
using System;

namespace Study02
{
    public class App
    {
        public App()
        {
            LCRSTree tree = new LCRSTree("A");
            var A = tree.root;
            var B = tree.AddChild(A, "B");
            var C = tree.AddChild(A, "C");

            var D = tree.AddSibling(B, "D");
            var E = tree.AddChild(B, "E");
            var F = tree.AddChild(B, "F");

            var G = tree.AddChild(D, "G");
        }
    }
}