コード例 #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;
            }
        }
コード例 #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();
        }
コード例 #3
0
ファイル: CustomTree.cs プロジェクト: veselints/DSA
        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);
        }
コード例 #4
0
ファイル: CustomTree.cs プロジェクト: veselints/DSA
        public bool Contains(CustomNode <string> nodeToAdd)
        {
            var result = this.treeNodes.Any(n => n.Value == nodeToAdd.Value);

            return(result);
        }