private static void TryPath(Node<int> startNode, int currentDepth, ref int maxPathCount)
        {
            while (true)
            {
                if (visited[nodeList.IndexOf(startNode)])
                {
                    if (currentDepth > maxPathCount)
                    {
                        maxPathCount = currentDepth;
                    }

                    return;
                }

                visited[nodeList.IndexOf(startNode)] = true;

                if (startNode.HasParent)
                {
                    startNode = startNode.Parent;
                    currentDepth = currentDepth + 1;
                    continue;
                }

                if (startNode.HasChildren)
                {
                    foreach (var child in startNode.Offspring)
                    {
                        TryPath(child, currentDepth + 1, ref maxPathCount);
                    }
                }

                break;
            }
        }
示例#2
0
        private static HashSet<string> FindAllSubtrees(Node<int>[] nodes, int searchedSum)
        {
            HashSet<string> subTrees = new HashSet<string>();

            foreach (var node in nodes)
            {
                if (node.Children.Count > 0)
                {
                    Queue<int> queue = new Queue<int>();

                    var sum = 0;
                    BFS(node, n => {

                        queue.Enqueue(n.Value);
                        sum += n.Value;

                        if (sum == searchedSum)
                        {
                            subTrees.Add(String.Join(" -> ", queue));
                            return false;
                        }

                        if (sum > searchedSum)
                        {
                            return false;
                        }

                        return true;                        
                    });
                }
            }

            return subTrees;
        }
示例#3
0
 public static void ProcessCross(Node a)
 {
     if (a != null)
     {
         ProcessDirect(a.Left);
         Visit(a);
         ProcessDirect(a.Right);
     }
 }
        public void Node_ShouldCallConstructor()
        {
            // Arrange
            var node = new Node<Int32>(10);
            var node2 = new Node<Int32>(node.Value + 1);

            // Act

            // Assert
        }
        public void SumAsStringTest()
        {
            var node = new Node<String>("Hello", new[]
            {
                new Node<String>(" World"),
                new Node<String>("!"),
            });
            //var result = NodeExtensions.Sum(node, false);
            var result = node.Sum((sum, child) => sum + child.Value);

            Assert.That(result, Is.EqualTo("Hello World!"));
        }
        public void SumTest()
        {
            var node = new Node<Int32>(23, new []
            {
                new Node<Int32>(10),
                new Node<Int32>(10),
            });
            //var result = NodeExtensions.Sum(node, false);
            var result = node.Sum();

            Assert.That(result, Is.EqualTo(43));
        }
示例#7
0
 public static void ProcessByLevels(Node a)
 {
     Queue<Node> q = new Queue<Node>();
     if (a != null)
     {
         q.Enqueue(a);
         while (q.Count != 0)
         {
             Node n = q.Dequeue();
             Visit(n);
             if (n.Left != null)
             {
                 q.Enqueue(n.Left);
             }
             if (n.Right != null)
             {
                 q.Enqueue(n.Right);
             }
         }
     }
 }
示例#8
0
        static void Main(string[] args)
        {
            // form tree
            Node a = new Node()
            {
                Name = "A"
            };
            a.Left = new Node()
            {
                Name = "B"
            };
            a.Right = new Node()
            {
                Name = "C"
            };

            ProcessReverse(a);
            //ProcessDirect(a);
            //ProcessByLevels(a);

            Console.Read();
        }
示例#9
0
        static void Main(string[] args)
        {

            // Test Input (hint: use Alt + LeftMouseClick to select multiple rows at once)
            //
            //7
            //2 4
            //3 2
            //5 0
            //3 5
            //5 6
            //5 1

            var N = int.Parse(Console.ReadLine());
            var nodes = new Node<int>[N];

            for (int i = 0; i < N; i++)
            {
                nodes[i] = new Node<int>(i);
            }

            for (int i = 1; i <= N - 1; i++)
            {
                string edgeAsString = Console.ReadLine();
                var edgeParts = edgeAsString.Split(' ');

                int parentId = int.Parse(edgeParts[0]);
                int childId = int.Parse(edgeParts[1]);

                nodes[parentId].Children.Add(nodes[childId]);
                nodes[childId].HasParent = true;
            }

            // 1. Find the root
            var root = FindRoot(nodes);
            Console.WriteLine("The root of the tree is: {0}", root.Value);

            //2. Find all leafs
            var leafs = FindAllLeafs(nodes);
            Console.WriteLine("Leafs: ");
            foreach (var leaf in leafs)
            {
                Console.Write("{0}, ", leaf.Value);
            }
            Console.WriteLine();

            //3. Find all middle nodes
            // For one node to be middle-node it must not be root and must have childrens
            var middleNodes = FindAllMiddleNodes(nodes);
            Console.WriteLine("Middle nodes: ");
            foreach (var node in middleNodes)
            {
                Console.Write("{0}, ", node.Value);
            }
            Console.WriteLine();

            //4. Find the longest path
            var longestPath = FindLongestPath(FindRoot(nodes));
            Console.WriteLine("Longest path from the root is: {0}", longestPath);

            //5. * all paths in the tree with given sum S of their nodes
            int searchedSum = 8;
            HashSet<string> allPaths = FindAllPathsWithSum(nodes, searchedSum);
            Console.WriteLine("Path/s with sum of {0} is/are: {1}", searchedSum, String.Join(" and ", allPaths));

            //6 * all subtrees with given sum S of their nodes
            searchedSum = 10;
            HashSet<string> allSubTrees = FindAllSubtrees(nodes, searchedSum);
            Console.WriteLine("Subtrees with sum of {0} is: {1}", searchedSum, string.Join(" and ", allSubTrees));

        }
示例#10
0
        static Node<int> FindRoot(Node<int>[] nodes)
        {
            var hasParent = new bool[nodes.Length];

            foreach (var node in nodes)
            {
                foreach (var child in node.Children)
                {
                    hasParent[child.Value] = true;
                }
            }

            for (int i = 0; i < hasParent.Length; i++)
            {
                if (!hasParent[i])
                {
                    return nodes[i];
                }
            }

            throw new ArgumentException("nodes", "The tree has no root.");
        }
示例#11
0
        private static 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;
        }
示例#12
0
        private static List<Node<int>> FindAllMiddleNodes(Node<int>[] nodes)
        {
            List<Node<int>> middleNodes = new List<Node<int>>();

            foreach (var node in nodes)
            {
                if (node.HasParent && node.Children.Count > 0)
                {
                    middleNodes.Add(node);
                }
            }

            return middleNodes;
        }
示例#13
0
        private static List<Node<int>> FindAllLeafs(Node<int>[] nodes)
        {
            List<Node<int>> leafs = new List<Node<int>>();

            foreach (var node in nodes)
            {
                if (node.Children.Count == 0)
                {
                    leafs.Add(node);
                }
            }

            return leafs;
        }
示例#14
0
        private static HashSet<string> FindAllPathsWithSum(Node<int>[] nodes, int searchedSum)
        {
            HashSet<string> treePaths = new HashSet<string>();

            foreach (var node in nodes)
            {
                if (node.Children.Count > 0)
                {
                    var stack = new Stack<int>();

                    var safeNode = node;
                    var sum = 0;
                    DFS(node, n => {
                        if (n.Parent == safeNode)
                        {
                            sum = safeNode.Value;
                            if (stack.Count > 1)
                            {
                                stack.Pop();
                            }
                        }

                        stack.Push(n.Value);
                        sum += n.Value;

                        if (sum == searchedSum)
                        {
                            treePaths.Add(String.Join(" -> ", stack.Reverse()));
                        }

                        if (sum > searchedSum)
                        {
                            stack.Pop();
                            sum -= n.Value;
                            return false;
                        }
                        return true;
                    });
                }
            }

            return treePaths;
        }
示例#15
0
        public static void DFS(Node<int> node, Func<Node<int>, bool> action)
        {
            Stack<Node<int>> stack = new Stack<Node<int>>();
            stack.Push(node);

            while (stack.Count > 0)
            {
                var n = stack.Pop();
                if (action != null)
                {
                    if (!action(n))
                    {
                        continue;
                    }
                }

                foreach (var child in n.Children)
                {
                    stack.Push(child);
                }
            }
        }
示例#16
0
        private static void BFS(Node<int> node, Func<Node<int>, bool> action)
        {
            Queue<Node<int>> queue = new Queue<Node<int>>();
            queue.Enqueue(node);

            while (queue.Count > 0)
            {
                var n = queue.Dequeue();
                if (action != null)
                {
                    if (!action(n))
                    {
                        queue.Clear();
                        continue;
                    }
                }

                foreach (var child in n.Children)
                {
                    queue.Enqueue(child);
                }
            }
        }
        private static IList<Node<int>> ReadInput()
        {
            if (File.Exists(@"..\..\input.txt"))
            {
                Console.SetIn(new StreamReader(@"..\..\input.txt"));
            }

            var n = int.Parse(Console.ReadLine());
            var nodes = new Node<int>[n];

            for (var i = 0; i < n; i++)
            {
                nodes[i] = new Node<int>(i);
            }

            for (var i = 1; i <= n - 1; i++)
            {
                var inputData = Console.ReadLine().Split().Select(int.Parse).ToArray();
                var parentId = inputData[0];
                var childId = inputData[1];
                nodes[parentId].AddChild(nodes[childId]);
                nodes[childId].AddPerent(nodes[parentId]);
            }

            return nodes;
        }
示例#18
0
 public static void Visit(Node n)
 {
     Console.WriteLine(n.Name);
 }