Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node<T>
- {
- public T Value { get; set; }
- public List<Node<T>> children { get; set; }
- public bool HasParent { get; set; }
- public Node()
- {
- this.children = new List<Node<T>>();
- }
- public Node(T value)
- : this()
- {
- this.Value = value;
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class Program
- {
- static void Main(string[] args)
- {
- int N = int.Parse(Console.ReadLine());
- Node<int>[] nodes = new Node<int>[N];
- for (int i = 0; i <= N; i++)
- {
- string edgeAsString = Console.ReadLine();
- string[] edgeParts = edgeAsString.Split(' ');
- int parent = int.Parse(edgeParts[0]);
- nodes[parent].Value = parent;
- int child = int.Parse(edgeParts[1]);
- nodes[parent].children.Add(new Node<int>(child));
- nodes[child].Value = child;
- nodes[child].HasParent = true;
- }
- }
- public Node<int> FindRoot(Node<int>[] nodes)
- {
- foreach (var node in nodes)
- {
- foreach (var child in node.children)
- {
- if (child.HasParent == false)
- {
- return child;
- }
- }
- }
- return null;
- }
- public List<Node<int>> FindAllLeafs(Node<int>[] nodes)
- {
- List<Node<int>> result = new List<Node<int>>();
- foreach (var node in nodes)
- {
- if (node.children == null)
- {
- result.Add(node);
- }
- }
- return result;
- }
- public List<Node<int>> FindMidleNodes(Node<int>[] nodes)
- {
- List<Node<int>> result = new List<Node<int>>();
- foreach (var node in nodes)
- {
- if (node.children.Count > 0 && node.HasParent == true)
- {
- result.Add(node);
- }
- }
- return result;
- }
- public int FindLongestPath(Node<int> root)
- {
- if (root.children.Count == 0)
- {
- return 0;
- }
- int maxPath = 0;
- foreach (var node in root.children)
- {
- maxPath = Math.Max(maxPath, FindLongestPath(node));
- }
- return maxPath + 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment