/* *Build a tree from given inputs and return the root node. */ public TreeNode BuildTree(IEnumerable<Input> inputs, TreeNode parentNode = null) { TreeNode rootNode = null; var inputDictionary = inputs.ToDictionary( // Building a dictionary to store each input and its corresponding node. This way we can create a Node and add it as a child of the given parent node. input => input.Id, input => new { Input = input, newNode = new TreeNode(input.Id) }); foreach (var value in inputDictionary.Values) // Iterating through the nodes so that we can add proper children for parents. { var input = value.Input; if (input.ParentId != null) //If the ParentId is null, add it as root. If not, add it as a child. { inputDictionary[(int)input.ParentId].newNode.AddChild(value.newNode); //Get the parentID for the input. Then get the node for the parentID and the add the child node to that parentNode. } else { rootNode = value.newNode; //If it does not have parent, its a root node. } } return rootNode; //throw new NotImplementedException(); }
public void AddChild(TreeNode id) { id.Parent = this; _internalChildren.Add(id); }