LCRS Tree

Algorithm 2023. 1. 16. 15:58
반응형
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructure
{
    //LCRS Tree
    class Tree
    {
        public class Node
        {
            public string data;
            public Node left;
            public Node right;
            //생성자 
            public Node(string data)
            {
                this.data = data;
            }
        }

        public Node root;

        //생성자 
        public Tree(string data) {
            this.root = new Node(data);
        }

        //자식 노드 추가 
        public Node AddChild(Node parent, string data) {
            if (parent == null) return null;
            Node child = new Node(data);
            if (parent.left == null)
            {
                parent.left = child;
            }
            else {
                var node = parent.left;
                while (node.right != null) {
                    node = node.right;
                }
                node.right = child;
            }
            return child;
        }

        //형제 노드 추가 
        public Node AddSibiling(Node node, string data) {
            if (node == null) return null;

            while(node.right != null)
            {
                node = node.right;
            }
            var sibiling = new Node(data);
            node.right = sibiling;
            return sibiling;
        }


        //레벨순으로 트리 노드 출력 
        public void PrintLevelOrder() {
            var q = new Queue<Node>();
            q.Enqueue(this.root);

            while (q.Count > 0) {
                var node = q.Dequeue();

                while (node != null) {
                    Console.Write("{0} ", node.data);
                    if (node.left != null) {
                        q.Enqueue(node.left);
                    }
                    node = node.right;
                }
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructure
{
    class App
    {
        public App() {
            Tree tree = new Tree("A");
            var A = tree.root;
            var B = tree.AddChild(A, "B");
            tree.AddChild(A, "C");
            var D = tree.AddSibiling(B, "D");
            tree.AddChild(B, "E");
            tree.AddChild(B, "F");
            tree.AddChild(D, "G");

            tree.PrintLevelOrder();
        }
    }
}

반응형

'Algorithm' 카테고리의 다른 글

[알고스팟] 록 페스티벌 C#  (0) 2023.01.17
BST (Binary Search Tree)  (0) 2023.01.16
[BOJ] 1874 스택 수열  (0) 2023.01.16
[BOJ] 9093 단어 뒤집기  (0) 2023.01.16
[BOJ] 1439 뒤집기  (0) 2023.01.16
: