Esempio n. 1
0
        private static void Main(string[] args)
        {
            int nodesCount = int.Parse(Console.ReadLine());

            for (int i = 1; i < nodesCount; i++)
            {
                string[]   edge        = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                int        parentValue = int.Parse(edge[0]);
                Tree <int> parentNode  = Tree <int> .GetTreeByNodeValue(parentValue);

                int        childValue = int.Parse(edge[1]);
                Tree <int> childNode  = Tree <int> .GetTreeByNodeValue(childValue);

                parentNode.Children.Add(childNode);
                childNode.Parent = parentNode;
            }

            int sumPath    = int.Parse(Console.ReadLine());
            int subtreeSum = int.Parse(Console.ReadLine());

            var rootNode = Tree <int> .FindRootNode();

            Console.WriteLine("Root node: {0}", rootNode.Value);

            var leafNodesValues = Tree <int> .FindLeafValues().Select(tree => tree.Value).OrderBy(value => value);

            Console.WriteLine("Leaf nodes: {0}", string.Join(",", leafNodesValues));

            var middleNodesValues = Tree <int> .FindMiddleValues().Select(tree => tree.Value).OrderBy(value => value);

            Console.WriteLine("Middle nodes: {0}", string.Join(",", middleNodesValues));

            var longestPath = Tree <int> .FindLongestPath();

            var length = longestPath.Count;

            Console.WriteLine(
                "Longest path: {0} (length = {1})",
                string.Join(" -> ", longestPath.Select(tree => tree.Value)),
                length);

            ICollection <IList <Tree <int> > > pathsWithGivenSum = FindAllPathsWithGivenSum(sumPath);

            PrintPathsWithGivenSum(pathsWithGivenSum, sumPath);

            ICollection <Tree <int> > subtreesWithGivenSum = new List <Tree <int> >();

            FindSubtreesWithGivenSum(subtreeSum, rootNode, subtreesWithGivenSum);
            PrintSubtreesWithGivenSum(subtreeSum, subtreesWithGivenSum);
        }