Delete nodes of tree data structure where children count is 0
Hi! I'm struggling to process a tree data structure I have. I want to delete all nodes where the count of children at level 3 is 0. How do I do this?
[DebuggerDisplay("{Value}")]
public class TreeViewModel<TId, TValue> : IEnumerable<TreeViewModel<TId, TValue>>
{
private readonly List<TreeViewModel<TId, TValue>> _children = new();
public TreeViewModel(TId id, TValue value, TreeViewModel<TId, TValue> parent = null)
{
Id = id;
Value = value;
Parent = parent;
}
public TId Id;
public TValue Value;
public TreeViewModel<TId, TValue> Parent;
public IReadOnlyList<TreeViewModel<TId, TValue>> Children => _children;
public bool IsRoot => Parent is null;
public bool IsLeaf => _children.Count == 0;
public int Level => IsRoot ? 0 : Parent.Level + 1;
public void AddChild(TId id, TValue value)
{
_children.Add(new TreeViewModel<TId, TValue>(id, value, this));
}
public void AddChild(TreeViewModel<TId, TValue> childTree)
{
childTree.Parent = this;
_children.Add(childTree);
}
public void AddChildren(Dictionary<TId, TValue> children)
{
foreach (var child in children)
AddChild(child.Key, child.Value);
}
public void RemoveChildren(Predicate<TreeViewModel<TId, TValue>> predicate)
{
_children.RemoveAll(predicate);
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<TreeViewModel<TId, TValue>> GetEnumerator()
{
yield return this;
foreach (var anyChild in Children.SelectMany(directChild => directChild))
{
yield return anyChild;
}
}
}
[DebuggerDisplay("{Value}")]
public class TreeViewModel<TId, TValue> : IEnumerable<TreeViewModel<TId, TValue>>
{
private readonly List<TreeViewModel<TId, TValue>> _children = new();
public TreeViewModel(TId id, TValue value, TreeViewModel<TId, TValue> parent = null)
{
Id = id;
Value = value;
Parent = parent;
}
public TId Id;
public TValue Value;
public TreeViewModel<TId, TValue> Parent;
public IReadOnlyList<TreeViewModel<TId, TValue>> Children => _children;
public bool IsRoot => Parent is null;
public bool IsLeaf => _children.Count == 0;
public int Level => IsRoot ? 0 : Parent.Level + 1;
public void AddChild(TId id, TValue value)
{
_children.Add(new TreeViewModel<TId, TValue>(id, value, this));
}
public void AddChild(TreeViewModel<TId, TValue> childTree)
{
childTree.Parent = this;
_children.Add(childTree);
}
public void AddChildren(Dictionary<TId, TValue> children)
{
foreach (var child in children)
AddChild(child.Key, child.Value);
}
public void RemoveChildren(Predicate<TreeViewModel<TId, TValue>> predicate)
{
_children.RemoveAll(predicate);
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<TreeViewModel<TId, TValue>> GetEnumerator()
{
yield return this;
foreach (var anyChild in Children.SelectMany(directChild => directChild))
{
yield return anyChild;
}
}
}
0 Replies