Exemplo n.º 1
0
        public void AttachChild(CustomNode <T> nodeToBecomeChild)
        {
            if (nodeToBecomeChild.parentNode != this)
            {
                if (nodeToBecomeChild.parentNode != null)
                {
                    throw new InvalidOperationException("The node has already a parent node.");
                }

                this.ChildNodes.Add(nodeToBecomeChild);
                nodeToBecomeChild.parentNode = this;
            }
        }
Exemplo n.º 2
0
        static void Main()
        {
            string stringNumberOfRows = Console.ReadLine().Trim();

            int numberOfRows;

            while (!int.TryParse(stringNumberOfRows, out numberOfRows))
            {
                Console.WriteLine("Invalid input");
            }

            var currentTree = new CustomTree();

            for (int i = 1; i < numberOfRows; i++)
            {
                string currentLine   = Console.ReadLine().Trim();
                string currentParent = currentLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
                string currentChild  = currentLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1];

                CustomNode <string> currentParentNode = new CustomNode <string>(currentParent);
                CustomNode <string> currentChildtNode = new CustomNode <string>(currentChild);

                var parent = currentTree.AddNode(currentParentNode);
                var child  = currentTree.AddNode(currentChildtNode);

                parent.AttachChild(child);
            }

            var rootNode = currentTree.FindRootNode().Value;

            Console.WriteLine("The root node is {0}", rootNode);
            Console.WriteLine();

            var allLeafs = currentTree.FindAllLeafs();

            foreach (var leaf in allLeafs)
            {
                Console.WriteLine("Leaf: {0}", leaf.Value);
            }
            Console.WriteLine();

            var allMiddle = currentTree.FindAllMiddleNodes();

            foreach (var leaf in allMiddle)
            {
                Console.WriteLine("Middle node: {0}", leaf.Value);
            }
            Console.WriteLine();
        }
Exemplo n.º 3
0
        public CustomNode <string> AddNode(CustomNode <string> nodeToAdd)
        {
            CustomNode <string> result;

            if (this.Contains(nodeToAdd))
            {
                result = this.treeNodes.FirstOrDefault(n => n.Value == nodeToAdd.Value);
            }
            else
            {
                this.treeNodes.Add(nodeToAdd);
                result = nodeToAdd;
            }

            return(result);
        }
Exemplo n.º 4
0
        public bool Contains(CustomNode <string> nodeToAdd)
        {
            var result = this.treeNodes.Any(n => n.Value == nodeToAdd.Value);

            return(result);
        }