I have a generic type tree class as follows:
public class TreeNode<T>
{
private readonly T _data;
private readonly TreeNode<T> _parent;
private readonly List<TreeNode<T>> _children;
private readonly int _level;
public int Level
{ get { return _level; } }
public int Count
{ get { return _children.Count; } }
public bool IsRoot
{ get { return _parent == null; } }
public bool IsLeaf
{ get { return _children.Count == 0; } }
public T Data
{ get { return _data; } }
public TreeNode<T> Parent
{ get { return _parent; } }
public TreeNode(T data)
{
_data = data;
_children = new List<TreeNode<T>>();
_level = 0;
}
public TreeNode(T data, TreeNode<T> parent) : this(data)
{
_parent = parent;
_level = _parent != null ? _parent.Level + 1 : 0;
}
public TreeNode<T> this[int key]
{
get { return _children[key]; }
}
public void AddChild(TreeNode<T> value)
{
_children.Add(value);
}
public TreeNode<T> GetChild(int key)
{
return _children[key];
}
public void Clear()
{
_children.Clear();
}
}
I want to create a function in this class to flatten all the nested children list, no matter how deep the tree is. The return value would be a list of TreeNode. The function can be used on any node, no matter it is root or not.
I tried solution using LINQ Flatten() but it seems to return only the first level. How can I design the function in the TreeNode class using LINQ (or not) so that no matter what type the node is I can always return such list?
You can create enumerator function to enumerate all children of a node. Here is an example of how to do it:
Converting to list will be simple:
Or if you have VERY deep tree we can emulate recursive algorithm: