3DMP 2022. 10. 27. 06:04
using System;
using System.Collections.Generic;

namespace TreeHeight
{

    class TreeNode<T>
    {
        public T data { get; set; }
        public List<TreeNode<T>> children { get; set; } = new List<TreeNode<T>>();
    }

    class Program
    {

        static TreeNode<string> makeTree()
        {
            TreeNode<string> root = new TreeNode<string>() { data = "Root" };
            {
                TreeNode<string> node = new TreeNode<string>() { data = "left" };
                node.children.Add(new TreeNode<string>() { data = "cc" });
                root.children.Add(node);
            }
            {
                TreeNode<string> node = new TreeNode<string>() { data = "design" };
                node.children.Add(new TreeNode<string>() { data = "combat" });
                node.children.Add(new TreeNode<string>() { data = "econo" });
                node.children.Add(new TreeNode<string>() { data = "abc" });
                root.children.Add(node);
            }
            {
                TreeNode<string> node = new TreeNode<string>() { data = "right" };
                node.children.Add(new TreeNode<string>() { data = "bb" });
                root.children.Add(node);
            }
            return root;
        }

        static int getTreeheight(TreeNode<string> root)
        {
            int height = 0;
            foreach(var elem in root.children)
            {
                int treeHeight = getTreeheight(elem) + 1;
                if(treeHeight > height)
                {
                    height = treeHeight;
                }
            }

            return height;
        }

        static void Main(string[] args)
        {
            var tree = makeTree();
            int treeHeight = getTreeheight(tree);
            Console.WriteLine(treeHeight);

        }
    }
}

 

결과는 2

 

 

 

반응형