我有一个树形结构,并且希望能够标记(例如颜色)从修改节点到根节点的节点。如果任何子节点标记为已修改,则父节点应标记为已修改。当子节点回到未修改状态时,应根据该节点的状态和其他子节点的状态来更新父节点。
我尝试过:
还有其他解决方案吗?
答案 0 :(得分:0)
您可以致电所有孩子,以检查他们是否已被修改。然后,他们依次给孩子打电话,例如
public class Node
{
public List<Node> Children { get; set; } = new List<Node>();
private bool _modified = false;
public bool HasBeenModified
{
get => _modified || Children.Any(c => c.HasBeenModified);
set => _modified = value;
}
}
可以添加一个有效的示例。
public static void Main(string[] args)
{
var parentNode = new Node();
var childNodeOne = new Node();
var childNodeTwo = new Node();
var childNodeOneOne = new Node();
childNodeOne.Children.Add(childNodeOneOne);
parentNode.Children.Add(childNodeOne);
parentNode.Children.Add(childNodeTwo);
// Check is currently not modified
Console.WriteLine($"Check: {parentNode.HasBeenModified}");
// Mark node 2 has modified and check again
childNodeTwo.HasBeenModified = true;
Console.WriteLine($"Check: {parentNode.HasBeenModified}");
// Unmark node 2 and make sure it's no longer modified
childNodeTwo.HasBeenModified = false;
Console.WriteLine($"Check: {parentNode.HasBeenModified}");
// Mark the second level child node as modified and check parent is also showing as modified
childNodeOneOne.HasBeenModified = true;
Console.WriteLine($"Check: {parentNode.HasBeenModified}");
Console.ReadKey();
}