public static Tree<int> GenerateTreeFtomTreeNodes(TreeNode<int>[] nodeArray) { bool[] isChild = new bool[nodeArray.Length]; foreach (var node in nodeArray) { if (node != null) { foreach (var child in node) { isChild[child.Value] = true; } } } for (int i = 0; i < isChild.Length; i++) { if (!isChild[i]) { Tree<int> tree = new Tree<int>(i); GenerateTreeFromFoor(tree, nodeArray); return tree; } } throw new ArgumentException("No root!!!"); }
private static TreeNode<int>[] GetNodesFtomConsole() { int nodeCount = 0; bool isAValidNumber = int.TryParse(Console.ReadLine(), out nodeCount); if (!isAValidNumber || nodeCount < 0) { throw new ArgumentException("You have to enter a valid positive integer for number of nodes!"); } TreeNode<int>[] nodes = new TreeNode<int>[nodeCount]; for (int i = 0; i < nodeCount; i++) { nodes[i] = new TreeNode<int>(i); } for (int i = 1; i <= nodeCount - 1; i++) { var pair = ReadPareFromConsole(); int parentId = pair.Item1; int childId = pair.Item2; nodes[parentId].AddChild(new TreeNode<int>(childId)); } return nodes; }
private static void GenerateTreeFromFoor(Tree<int> tree, TreeNode<int>[] nodeArray) { foreach (TreeNode<int> node in nodeArray[tree.Root.Value]) { tree.Root.AddChild(node); GenerateSubnodes(node, nodeArray); } }
private static void GenerateSubnodes(TreeNode<int> node, TreeNode<int>[] nodeArray) { foreach (TreeNode<int> subnode in nodeArray[node.Value]) { node.AddChild(subnode); GenerateSubnodes(subnode, nodeArray); } }