I have tree node defined like this:
class TreeNode : IEnumerable<TreeNode>
{
private readonly Dictionary<string, TreeNode> _childs = new Dictionary<string, TreeNode>();
public readonly string ID;
public TreeNode Parent { get; private set; }
public int Level { get; set; }
public TreeNode(string id)
{
this.ID = id;
}
// some other methods
}
I created tree from keywords by this and now I have sometimes branch where parent tree node has one child and that child could have one child too and after some nodes there are 2 childs. So I want now to reduce all that one child (remove it) to “level” where there are at least 2 child nodes.
I tried something like this:
private void TreeReduction(TreeNode node)
{
while (node.Count() == 1)
{
node = node.GetFirstChild();
}
foreach (var child in node)
{
TreeReduction(child);
}
}
and I call it to main node. It’s look okay and it’s going through tree but that nodes aren’t rewrite. I tried out parameter for treenode but I have problem with foreach loop. How can I fix it to have it working? Thanks
Making many assumptions about what would happen, for example to single-branch single-leaf tree, you could go for something like this.
Aside this, the key point is for your recursive method to return a TreeNode which you will be able to set as childnode.
I Left out the Parent property as its setter is private. If AddChild does not set it, you should make it public and carry it as a parameter.